Simplexml_load_string () will not read the soap response using "soap:" in tags

I know this may be a question for beginners, but please humor me. When reading an xml string with "soap:" in simplexml_load_string () tags will not read in xml.

given this script:

#!/usr/bin/php <?php $s=' <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"> <soap:Header> <context xmlns="urn:zimbra"/> </soap:Header> <soap:Body> <AuthResponse xmlns="urn:zimbraAdmin"> <authToken>somevalue</authToken> <lifetime>123124123</lifetime> <an="zimbraIsDomainAdminAccount">false</a> </AuthResponse> </soap:Body> </soap:Envelope>'; print_r(simplexml_load_string($s)); echo "\n\n"; print_r(simplexml_load_string(str_ireplace("soap:", "", $s))); ?> 

I get this output:

 jesse@jesse-debian :~/code/zmsoap$ ./xmltest.php SimpleXMLElement Object ( ) SimpleXMLElement Object ( [Header] => SimpleXMLElement Object ( [context] => SimpleXMLElement Object ( ) ) [Body] => SimpleXMLElement Object ( [AuthResponse] => SimpleXMLElement Object ( [authToken] => somevalue [lifetime] => 123124123 [a] => false ) ) ) jesse@jesse-debian :~/code/zmsoap$ 

I'm just wondering why this is happening, and if there is a better way to fix the problem, rather than replace the string.

+6
source share
3 answers

A colon tag name indicates that the tag is in a namespace other than the default. SimpleXML considers only one namespace at a time, so you need to specifically select the namespace using the ->children() method .

In this case, $xml->children('http://www.w3.org/2003/05/soap-envelope')->Body or $xml->children('soap', true)->Body should work .

For this and other reasons, it is not practical to use print_r to debug SimpleXML objects. Try this highlighted feature .

+12
source

It seems to have worked.

Read about it here: Parse XML using a namespace using SimpleXML

 #!/usr/bin/php <?php $s=' <soap:Envelope xmlns:soap="urn:zimbra"> <soap:Header> <context xmlns="urn:zimbra"/> </soap:Header> <soap:Body> <AuthResponse xmlns="urn:zimbraAdmin"> <authToken>somevalue</authToken> <lifetime>123124123</lifetime> <an="zimbraIsDomainAdminAccount">false</a> </AuthResponse> </soap:Body> </soap:Envelope>'; //print_r(simplexml_load_string($s)); //echo "\n\n"; //print_r(simplexml_load_string(str_ireplace("soap:", "", $s))); $xml = simplexml_load_string($s); $xml->registerXPathNamespace("soap", "http://www.w3.org/2003/05/soap-envelope"); print_r($xml->xpath('//soap:Body')); ?> 
+5
source

The simplest:

 $xml='<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><AddOrderResult>1</AddOrderResult></soap:Body></soap:Envelope>'; var_export(json_decode(json_encode(simplexml_load_string(strtr($xml, array(' xmlns:'=>' ')))), 1)); 

exit:

 array ( '@attributes' => array ( 'soap' => 'http://schemas.xmlsoap.org/soap/envelope/', ), 'soap:Body' => array ( 'AddOrderResult' => '1', ), ) 
0
source

Source: https://habr.com/ru/post/925724/


All Articles