试图用simplexmlphp解析

问题描述

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Header/>
    <SOAP-ENV:Body>
    <SOAP-ENV:Fault>
    <faultcode>SOAP-ENV:Client</faultcode>
    <faultstring xml:lang="en">MerchantException</faultstring>
    <detail>store id is missing</detail>
    </SOAP-ENV:Fault>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

我尝试了以下代码获取'detail'标签,但始终出现空白:

$xml = simplexml_load_string($result);
$posts = $xml->children('SOAP-ENV',true)->Body->children('SOAP-ENV',true)->Fault;
foreach ($posts as $post)
  {
    echo $post->detail;  
}

感激的帮助

解决方法

使用children()时,需要对SimpleXML所使用的名称空间进行某种更改。由于<detail>在默认名称空间中,因此需要(再次)将其使用的名称空间更改为默认名称空间。通过使用children()且未定义命名空间...

echo $post->children()->detail;

测试代码是...

$result = '<SOAP-ENV:Envelope
    xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Header />
    <SOAP-ENV:Body>
        <SOAP-ENV:Fault>
            <faultcode>SOAP-ENV:Client</faultcode>
            <faultstring xml:lang="en">MerchantException</faultstring>
            <detail>store id is missing</detail>
        </SOAP-ENV:Fault>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>';

$xml = simplexml_load_string($result);
$posts = $xml->children('SOAP-ENV',true)->Body->children('SOAP-ENV',true)->Fault;
foreach ($posts as $post)
{
    echo $post->children()->detail;
}

显示...

store id is missing