PHP SimpleXml - 检索命名空间子项的属性 [英] PHP SimpleXml - Retrieving attributes of namespaced children

查看:32
本文介绍了PHP SimpleXml - 检索命名空间子项的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解析外部 Atom 提要,一些条目具有命名空间子项的集合 - 我无法从这些子项中检索属性.缩略示例:

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?

推荐答案

试试这个

    $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/>";
        }
    }

这篇关于PHP SimpleXml - 检索命名空间子项的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆