Php XML xpath属性值
如何获取xml xpath输出的属性值Php XML xpath属性值,php,xml,simplexml,Php,Xml,Simplexml,如何获取xml xpath输出的属性值 Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => c ) ) [1] => SimpleXMLElement Object (
Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[name] => c
)
)
[1] => SimpleXMLElement Object
(
[@attributes] => Array
(
[name] => change management
)
)
[2] => SimpleXMLElement Object
(
[@attributes] => Array
(
[name] => coaching
)
)
)
这是我的目标,我需要提取价值观“c”、“变革管理”和“辅导”
这就是我的xml的样子
<Competency name="c">
</Competency>
<Competency name="change management">
</Competency>
<Competency name="coaching">
</Competency>
结果
c
change management
coaching
simplexmlement::xpath()
始终返回simplexmlement
对象的数组。即使表达式返回属性节点列表。在这种情况下,属性节点将转换为simplexmlement
实例。如果将它们强制转换为字符串,则将获得属性值:
$element = new SimpleXMLElement($xml);
foreach ($element->xpath('//Competency/@name') as $child) {
var_dump(get_class($child), (string)$child);
}
输出:
string(16) "SimpleXMLElement"
string(1) "c"
string(16) "SimpleXMLElement"
string(17) "change management"
string(16) "SimpleXMLElement"
string(8) "coaching"
如果这太神奇了,您需要使用DOM。它更加可预测和明确:
$document = new DOMDocument($xml);
$document->loadXml($xml);
$xpath = new DOMXPath($document);
foreach ($xpath->evaluate('//Competency/@name') as $attribute) {
var_dump(get_class($attribute), $attribute->value);
}
string(7) "DOMAttr"
string(1) "c"
string(7) "DOMAttr"
string(17) "change management"
string(7) "DOMAttr"
string(8) "coaching"
我会使用DOMDocument解析器,它有更多的选项,更易于使用。如果您喜欢xpath,请阅读以下内容:
$document = new DOMDocument($xml);
$document->loadXml($xml);
$xpath = new DOMXPath($document);
foreach ($xpath->evaluate('//Competency/@name') as $attribute) {
var_dump(get_class($attribute), $attribute->value);
}
string(7) "DOMAttr"
string(1) "c"
string(7) "DOMAttr"
string(17) "change management"
string(7) "DOMAttr"
string(8) "coaching"