在PHP中使用DOMDocument访问带有名称空间的元素的问题


Problems accessing elements with namespaces in PHP using DOMDocument

这是我的XML片段:

<?xml version="1.0" encoding="UTF-8"?>
<ns:searchResult xmlns:ns="http://outerx.org/daisy/1.0">
...
    <ns:rows>
        <ns:row documentId="1440-DFO_MPO" branchId="1" languageId="2"
            access="read,fullRead,write,publish">
            <ns:value>1440-DFO_MPO</ns:value>
            <ns:value>Navigation for Multimedia</ns:value>
        </ns:row>
    </ns:rows>
...

这是我当前的PHP代码:

$dom = new DOMDocument();
$dom->load($xml);
$docs = $dom->getElementsByTagNameNS('http://outerx.org/daisy/1.0','row');
print "<ul>";
$c = 0;    
foreach ($docs as $elem) {
    print "<li>".$c."</li>";
    $c = $c + 1;
}    
print "</ul>";

当然,这个代码片段应该输出一个基于XML片段的项目列表。然而,它没有。

我也试过了(没有成功):

$docs = $dom->getElementsByTagName('row');

编辑#1 -解决方案

修改dom ->加载($ xml)美元dom -> loadXML ($ xml);

你的代码为我工作。我假设您在$xml中传递XML内容,而load()期望它是文件名或URI。要直接加载XML内容,您必须使用

  • DOMDocument::loadXML -从字符串加载XML

见http://codepad.org/oy3U1fmE