如何使用PHP的simplexml_load_string获取XML标记(包含名称空间)的值?

时间:2013-11-10 10:31:07

标签: php xml soap

如何从以下XML获取“TagOne”(即foo)和TagTwo(即bar)的值 的 simplexml_load_string ?我被标签中名为“ns”的名称空间所困扰。

<?xml version="1.0" encoding="UTF-8"?>

<SOAP-ENV:Body>

    <ns:ExampleInterface_Output xmlns:ns="http://example.com/interfaces">
        <ns:TagOne>Foo</ns:TagOne>
        <ns:TagTwo>Bar</ns:TagTwo>
    </ns:ExampleInterface_Output>

</SOAP-ENV:Body>

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

那么你可以像这样声明“ns”命名空间到simplexml_load_string:

$xml = simplexml_load_string($string, "SimpleXMLElement", 0, "ns", TRUE);

这表示“ns”是名称空间前缀(而不是名称空间URL)。有关详细信息,请参阅PHP doc page for simplexml_load_string

另一个问题是Body元素具有“SOAP-ENV”前缀,该前缀未在XML中的任何位置声明,因此您将收到有关此内容的警告。但是,$xml的值将成为如下结构的对象:

SimpleXMLElement Object (
    [ExampleInterface_Output] => SimpleXMLElement Object (
        [TagOne] => Foo
        [TagTwo] => Bar
    )
)

但是,除了警告之外,这可能正是您所需要的。如果警告有问题,您只需从Body元素的开始和结束标记中删除“SOAP-ENV”前缀。

答案 1 :(得分:0)

检查此代码:

<?php

$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                   xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <SOAP-ENV:Body>
        <ns:ExampleInterface_Output xmlns:ns="http://example.com/interfaces">
            <ns:TagOne>Foo</ns:TagOne>
            <ns:TagTwo>Bar</ns:TagTwo>
        </ns:ExampleInterface_Output>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
XML;

$xse = new SimpleXMLElement($xml);
$exampleInterface = $xse
    ->children('SOAP-ENV', true)
    ->children('ns', true);

foreach ($exampleInterface->children('ns', true) as $key => $value) {
    //Do your stuff
}