用PHP读取XML.无效(命名空间)


Reading XML with PHP. Not work (namespaces)

我可以读取XML文件或字符串,但不能读取下一个:

$str = <<<XML
    <Output xmlns="nice.uniform://" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <Data i:nil="true"/>
        <Result xmlns:a="http://nice.uniform/CLSAPI3">
            <a:ResultCode>SUCCESS</a:ResultCode>
            <a:ResultMessage>OK</a:ResultMessage>
            <a:ResultCodeEx>CLS_SE_SUCCESS</a:ResultCodeEx>
        </Result> 
        <Exception i:nil="true" xmlns:a="http://schemas.datacontract.org/2004/07/System"/>
    </Output>
XML;

我读取XML文件节点的PHP代码是:

$Output = new SimpleXMLElement($str);
echo $Output->Result->{'a:ResultCodeEx'};

此外,我也尝试过:

$xmlResponse = simplexml_load_file('file.xml');
foreach($xmlResponse->Result as $xmlEntry)
{
 echo $xmlEntry->{'a:ResultCodeEx'};
}

//或

$blocks = $xmlResponse->xpath('//Output');
print_r($blocks);

你能帮我吗?

文档使用了几个名称空间。元素ResultCodeEx属于名称空间a。您可以使用XPath,但需要在查询之前注册名称空间a

$Output = new SimpleXMLElement($str);
$Output->registerXPathNamespace ('a', 'http://nice.uniform/CLSAPI3');
$result =  $Output->xpath('//a:ResultCodeEx/text()');
echo $result[0]; // CLS_SE_SUCCESS