问题
I'm parsing an external Atom feed, some entries have a collection of namespaced children - I'm failing to retrieve attributes from those children. Abbreviated example:
$feed = <<<EOD
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:ai="http://activeinterface.com/thincms/2012">
<entry>
<title>Some Title</title>
<ai:image>path/to/some/image</ai:image>
<ai:ocurrence dateid="20120622" date="Fri, June 22, 2012" time="6:00 pm" />
<ai:ocurrence dateid="20120720" date="Fri, July 20, 2012" time="6:00 pm" />
</entry>
</feed>
EOD;
$xml = new SimpleXmlElement($feed);
foreach ($xml->entry as $entry){
echo $entry->title;
$namespaces = $entry->getNameSpaces(true);
$ai = $entry->children($namespaces['ai']);
echo $ai->image;
foreach($ai->ocurrence as $o){
echo $o['date'];
}
}
Everything but the attribute retrieval of the namespaced children works fine - if the children's tagnames aren't namespaced, it works fine. If grabbing the node value (rather than an attribute), even if namespaced, it works fine. What am I missing?
回答1:
Try this
$xml = new SimpleXmlElement($feed);
foreach ($xml->entry as $entry)
{
$namespaces = $entry->getNameSpaces(true);
$ai = $entry->children($namespaces['ai']);
foreach ($ai->ocurrence as $o)
{
$date=$o->attributes();
echo $date['date'];
echo "<br/>";
}
}
回答2:
don't know why, but apparently array access won't work here... need the attributes method:
echo $o->attributes()->date;
来源:https://stackoverflow.com/questions/10663318/php-simplexml-retrieving-attributes-of-namespaced-children