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:


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">
    $dom = new DOMDocument( '1.0', 'utf-8' );
    $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
    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥100 需求高精度PT100设计电路和算法
  • ¥15 单片机配网,继电器开关,广播
  • ¥60 Qcustomplot绘制实时动态曲线
  • ¥20 运用matlab画x-y图
  • ¥15 用idea运行项目,运行tomcat报错:断言失败
  • ¥15 Sqlserver查询链接服务器数据问题
  • ¥15 Bibtex4Word 引用中文文献
  • ¥20 用opencv c/c++ 转换成灰度图,然后做一下直方图均衡,输出mp4文件
  • ¥20 matlab中的双层数值积分
  • ¥50 服务器打印水晶报表问题