使用 PHP SimpleXML 解析命名空间时出现问题


Issue parsing namespaces using PHP SimpleXML

我有这个xml内容:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<ns3:searchResult total="1" xmlns:ns5="ers.ise.cisco.com" xmlns:ers-v2="ers-v2" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:ns3="v2.ers.ise.cisco.com">
<ns3:resources>
<ns5:resource id="42e98860-cb88-11e5-9b0c-000c29c658fa" name="11:22:33:44:55:66">
<link rel="self" href="https://1.2.3.4:9060/ers/config/endpoint/42e98860-cb88-11e5-9b0c-000c29c658fa" type="application/xml"/>
</ns5:resource>
</ns3:resources>
</ns3:searchResult>

我需要获取 ns5:Resource ID 值的值 (42E98860-cb88-11e5-9b0c-000c29c658fa),但是在每个节点中使用命名空间让我感到困惑,我尝试使用 $xml->children('ns5',true)->resource->id 和我尝试的所有内容都给了我空的 simplexml 对象。

有什么建议吗?

我认为您可以使用这个 xpath 表达式:

$elements = $xml->xpath('/ns3:searchResult/ns3:resources/ns5:resource');

xpath将返回一个数组,您可以从该数组中获取第一项。该项的类型为 SimpleXMLElement,您可以从其属性中获取 ID。

$source = <<<SOURCE
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<ns3:searchResult total="1" xmlns:ns5="ers.ise.cisco.com" xmlns:ers-v2="ers-v2" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:ns3="v2.ers.ise.cisco.com">
<ns3:resources>
<ns5:resource id="42e98860-cb88-11e5-9b0c-000c29c658fa" name="11:22:33:44:55:66">
<link rel="self" href="https://1.2.3.4:9060/ers/config/endpoint/42e98860-cb88-11e5-9b0c-000c29c658fa" type="application/xml"/>
</ns5:resource>
</ns3:resources>
</ns3:searchResult>
SOURCE;
$xml = simplexml_load_string($source);
$elements = $xml->xpath('/ns3:searchResult/ns3:resources/ns5:resource');
$element = $elements[0];
echo $element->attributes()->id->__toString();

将导致:

42E98860-CB88-11E5-9B0C-000C29C658FA