dongya2029 2013-04-09 05:02
浏览 65

使用php domxml读取xml文件时出错?

I have a file test.xml

<?xml version="1.0" encoding="UTF-8"?>
<item>
<dc:creator><![CDATA[hello world]]></dc:creator>
</item>

and code php

$doc = new DOMDocument();
$doc->load('test.xml');
$items = $doc->getElementsByTagName('item');
foreach ($items as $item) {
   $authors = $item->getElementsByTagName( "dc:creator" );
   $author = $authors->item(0)->nodeValue;
   echo $author;
}

=> error can't get value, how to get this, result is "hello world"

  • 写回答

1条回答 默认 最新

  • douzhang1115 2013-04-09 08:08
    关注

    You are using the wrong element name. The method getElementsByTagName expects the local-name, that is creator in your case.

    You can see that if you load your sample XML

    <?xml version="1.0" encoding="UTF-8"?>
    <item>
    <dc:creator><![CDATA[hello world]]></dc:creator>
    </item>
    

    into the DOMDocument. You get a warning:

    Warning: DOMDocument::loadXML(): Namespace prefix dc on creator is not defined in Entity

    Because the namespace prefix is not defined, DOMDocument will remove it. This results in the following XML:

    <?xml version="1.0" encoding="UTF-8"?>
    <item xmlns:dc="ns:1">
    <creator><![CDATA[hello world 2]]></creator>
    </item>
    

    As you can see there is no element with the local name creator with an xmlns-prefix dc (<dc:creator>)any longer.

    But as you're like have pasted the wrong XML for your example and likely the namespace prefix is defined in your real XML, you're just asking how to access tags with a namespace prefix (that is the part before the colon :). This has already been outlined here:

    If you want an element which's tag is inside a namespace of its own, you need to tell DOMDocument which namespace you mean:

    $dcUri   = $doc->lookupNamespaceUri('dc');
    $authors = $item->getElementsByTagNameNS($dcUri, 'creator');
    $author  = $authors->item(0)->nodeValue;
    
    评论

报告相同问题?

悬赏问题

  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线