doyrte8419
doyrte8419
2013-11-10 10:31

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

已采纳

How do I get the value of "TagOne" (i.e. foo) and TagTwo (i.e. bar) from the XML below using simplexml_load_string? I'm stumped by the namespace called "ns" in the tag.

<?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>

Thanks very much for your kind help!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dourunlao1642 dourunlao1642 8年前

    Check this code:

    <?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
    }
    
    点赞 评论 复制链接分享
  • doutang6600 doutang6600 8年前

    Well you can declare the "ns" namespace to simplexml_load_string like this:

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

    This says that "ns" is a namespace prefix (rather than a namespace URL). See the PHP doc page for simplexml_load_string for more details.

    Another problem is that the Body element has a "SOAP-ENV" prefix which is not declared anywhere in the XML, so you will get a warning about this. However, the value of $xml will become an object structured like this:

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

    But, warning aside, this might be exactly what you need. If the warning is a problem, you can simply remove the "SOAP-ENV" prefix from the start and end tags of the Body element.

    点赞 评论 复制链接分享

为你推荐