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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入