douyu9433 2018-01-25 00:46
浏览 122
已采纳

使用PHP DOMDocument从带有冒号的命名空间的xml节点获取值

I'm parsing xml document using DOMDocument class. First I've selected all nodes with name 'item' using $xml->getElementsByTagName('item') method. My sample xml file looks like this:

<item>
      <title>...</link>
      <description>...</description>
      <pubDate>...</pubDate>
      <ns:author>...</dc:creator>
</item>

However my problem is getting value from nested tag with namespace name with colon sign. I get values from nodes without namespaces in foreach using $node->getElementsByTagName('description')->item(0)->nodeValue and there is no errors.

I also found method getElementsByTagNameNs() to get nodes with it's namespaces. However when i try to get nodeValue like previous nodes without namespace I get "PHP Notice: Trying to get property of non-object". I think it is strange because getElementsByTagNameNs()->item(0) returns object DOMElement.

Do you know how to take value from node with namespace, in this case <ns:author></dc:creator> element?

  • 写回答

1条回答 默认 最新

  • doubiao7410 2018-01-25 11:48
    关注

    As the document fragment you give isn't complete and even valid, I've had to make a few changes. You say you want the value of <ns:author>...</dc:creator> which is not a valid element as the open and close names are different in both name and namespace, you would expect something like <ns:author>...</ns:author>

    As an example of how you can fetch the values from a namespace (using some corrected and some guessed alterations to the XML)...

    $xml = <<<XML
    <?xml version="1.0"?>
    <items xmlns:ns="http://some.url">
        <item>
          <title>title</title>
          <description>Descr.</description>
          <pubDate>1/1/1970</pubDate>
          <ns:author>author1</ns:author>
        </item>
    </items>
    XML;
    
    $dom = new DOMDocument( '1.0', 'utf-8' );
    $dom->loadXML($xml);
    $items = $dom->getElementsByTagName('item');
    foreach ( $items as $item )  {
        $author = $item->getElementsByTagNameNS("http://some.url", "*")->item(0)->nodeValue;
        echo "Author = ".$author.PHP_EOL;
    }
    

    In getElementsByTagNameNS() you will need to put in the correct URL for this namespace, which should be in the source document.

    This outputs...

    Author = author1
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作