1

如何使用 simplexml_load_string从下面的 XML 中获取“TagOne”(即 foo)和 TagTwo(即 bar)的值?我被标签中名为“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>

非常感谢您的帮助!

4

2 回答 2

0

好吧,您可以像这样将“ns”命名空间声明为 simplexml_load_string:

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

这表示“ns”是命名空间前缀(而不是命名空间 URL)。有关更多详细信息,请参阅simplexml_load_string 的 PHP 文档页面。

另一个问题是Body元素有一个“SOAP-ENV”前缀,它没有在 XML 的任何地方声明,所以你会得到一个警告。但是, 的值$xml将变成一个结构如下的对象:

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

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

于 2013-11-10T11:21:46.190 回答
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
}
于 2013-11-10T11:26:34.393 回答