【问题标题】:Parse XML multiple namespaces with php SimpleXML使用 php SimpleXML 解析 XML 多个命名空间
【发布时间】:2016-09-22 07:03:33
【问题描述】:

例如,我的问题有很多答案 Parse XML namespaces with php SimpleXML 但我不明白在我的情况下如何调整代码以读取值?我有一个命名空间 m: 在命名空间肥皂内: 我需要解析这个 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>

【问题讨论】:

标签: php xml soap namespaces


【解决方案1】:

您需要根据您的 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(
  )),
)

【讨论】:

    猜你喜欢
    • 2013-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    相关资源
    最近更新 更多