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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog