使用php SimpleXML解析XML多个名称空间

时间:2016-05-24 21:27:10

标签: php xml soap namespaces

例如,我的问题有很多答案 Parse XML namespaces with php SimpleXML但我无法理解如何调整代码以便在我的情况下读取值?我有一个命名空间m:在命名空间soap内: 我需要解析这个XML并只提取值888-0000019749

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
        <soap:Body>
        <m:SaveDocumentsResponse xmlns:m="http://www.cargo3.ru">
            <m:return xmlns:xs="http://www.w3.org/2001/XMLSchema"
                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                <m:Key>SaveDocuments</m:Key>
                <m:List>
                    <m:Key>Order</m:Key>
                    <m:Properties>
                        <m:Key>Number</m:Key>
                        <m:Value xsi:type="xs:string">888-0000019749</m:Value>
                        <m:ValueType>string</m:ValueType>
                    </m:Properties>
                    <m:Properties>
                        <m:Key>CreateDate</m:Key>
                        <m:Value xsi:type="xs:dateTime">2016-05-23T20:56:50</m:Value>
                        <m:ValueType>dateTime</m:ValueType>
                    </m:Properties>
                </m:List>
            </m:return>
        </m:SaveDocumentsResponse>
        </soap:Body>
</soap:Envelope>

也无法管理这个例子 parse an XML with SimpleXML which has multiple namespaces 试图

$xml = simplexml_load_string($res, NULL, NULL, "http://schemas.xmlsoap.org/soap/envelope/");
$xml->registerXPathNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/');
$xml->registerXPathNamespace('m', 'http://www.w3.org/2001/XMLSchema');

foreach($xml->xpath('//m:SaveDocumentsResponse') as $header)
{
    var_export($header->xpath('//m:return')); // Should output 'something'.

}

我又错过了一些东西......

再次

echo $list = (string)$xml->children('soap', true)->Body->children('m', true)->SaveDocumentsResponse->return->List;

我需要最简单,最简单的方法从

中提取价值
<m:Value xsi:type="xs:dateTime">2016-05-23T20:56:50</m:Value>

1 个答案:

答案 0 :(得分:0)

您需要根据XML数据将前缀映射到相应的名称空间URI。因此,根据您的XML,您的前缀需要映射到URI“http://www.cargo3.ru”:

$xml->registerXPathNamespace('m', 'http://www.cargo3.ru');

foreach($xml->xpath('//m:SaveDocumentsResponse') as $header)
{
    var_export($header->xpath('//m:return')); // Should output 'something'.
}

<强> eval.in demo

输出

array (
  0 => 
  SimpleXMLElement::__set_state(array(
  )),
)