dqjgf0982
2014-04-11 11:45
浏览 37

用PHP读取XML。 不起作用(命名空间)

I can read XML files or strings but not the next:

$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;

My PHP code to read a node of XML file is:

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

Also, I've tried:

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

//or

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

Can you help me?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongwubao4785 2014-04-11 11:52
    已采纳

    The document uses several namespaces. The element ResultCodeEx belongs to the namespace a. You can use XPath, but you need to register the namespace a before the query:

    $Output = new SimpleXMLElement($str);
    $Output->registerXPathNamespace ('a', 'http://nice.uniform/CLSAPI3');
    $result =  $Output->xpath('//a:ResultCodeEx/text()');
    echo $result[0]; // CLS_SE_SUCCESS
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题