PHP 如何使用 PHP 读取字符串中的 XML 子节点值?
问题描述:
我有一个从其他服务器动态获取其值的字符串.字符串的值为
I have a String which gets its value dynamically from other server. Value of string is
$string1 = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.microsoft.com/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<AuthenticateUserResponse xmlns="http://microsoft.com/xml/namespace/2012/04">
<Authenticator>AE1001</Authenticator>
</AuthenticateUserResponse>
</soap:Body>
</soap:Envelope>';
我的问题是,通常我们使用 *$xml = simplexml_load_file("test1.xml");* 来加载 XML 文件,但在我的要求中它是一个 String,我怎么读这个字符串值并提取子节点及其值?示例:
My Question is, generally we use *$xml = simplexml_load_file("test1.xml");* to load XML files, but here in my requirement it is a String, how can i read this String value and extract the child node and its value? Example:
以及它的值AE1001"?
有没有办法把它放到数组中?这样我就可以轻松打印出它的节点值?
Is there a way to put this into Array? so that its easy for me to print out its node value?
答
同时学习 DOMDocument 和 XPath.真的很值得花时间.
Also learn DOMDocument and XPath. It really worth the time.
$doc = new DOMDocument;
$doc->loadXML($string1);
echo $doc->getElementsByTagName('Authenticator')->item(0)->nodeValue; // AE1001