問題描述
我知道這可能是一個新手問題,但請逗我笑.當讀取標簽中帶有soap:"的 xml 字符串時,simplexml_load_string() 不會讀取到 xml.
I know this may be a newbie question, but please humor me. When reading an xml string with "soap:" in the tags, simplexml_load_string() will not read in the xml.
給定這個腳本:
#!/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>
<a n="zimbraIsDomainAdminAccount">false</a>
</AuthResponse>
</soap:Body>
</soap:Envelope>';
print_r(simplexml_load_string($s));
echo "
";
print_r(simplexml_load_string(str_ireplace("soap:", "", $s)));
?>
我得到這個輸出:
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 curious why this is happening, and if there is a more proper way to remedy the problem as opposed to doing a string replace.
推薦答案
帶有冒號 in 的標記名稱表示該標記位于非默認命名空間中.SimpleXML 一次只查看一個命名空間,因此您需要使用 ->children()
方法.
A tag name with a colon in indicates the tag is in a non-default namespace. SimpleXML only looks at one namespace at a time, so you need to specifically select the namespace using the ->children()
method.
在這種情況下 $xml->children('http://www.w3.org/2003/05/soap-envelope')->Body
或 $xml->children('soap', true)->Body
應該都可以.
In this case $xml->children('http://www.w3.org/2003/05/soap-envelope')->Body
or $xml->children('soap', true)->Body
should both work.
出于這個和其他原因,不建議使用 print_r
來調試 SimpleXML 對象.試試這個專用功能.
For this and other reasons, it's not advisable to use print_r
to debug SimpleXML objects. Try this dedicated function instead.
這篇關于simplexml_load_string() 不會讀取帶有“soap:"的soap響應;在標簽中的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!