PHP SimpleXml - Retrieving attributes of namespaced children

感情迁移 提交于 2019-12-25 02:34:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!