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 filenotfounderror:文件是存在的,权限也给了,但还一直报错
  • ¥15 YOLOv5在进行trainpy训练后为什么会出现这种情况(语言-python)
  • ¥15 关于远程桌面的鼠标位置转换
  • ¥15 MATLAB和mosek的求解问题
  • ¥20 修改中兴光猫sn的时候提示失败
  • ¥15 java大作业爬取网页
  • ¥15 怎么获取欧易的btc永续合约和交割合约的5m级的历史数据用来回测套利策略?
  • ¥15 有没有办法利用libusb读取usb设备数据
  • ¥15 为什么openeluer里面按不了python3呢?
  • ¥15 关于#matlab#的问题:训练序列与输入层维度不一样