How can i get the attribute value of an xml xpath output ?
Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[name] => c
)
)
[1] => SimpleXMLElement Object
(
[@attributes] => Array
(
[name] => change management
)
)
[2] => SimpleXMLElement Object
(
[@attributes] => Array
(
[name] => coaching
)
)
)
This is my Object and i need to extract the values "c", "change management" and "coaching"
This is how my xml look like
<Competency name="c">
</Competency>
<Competency name="change management">
</Competency>
<Competency name="coaching">
</Competency>
foreach ($xml->Competency as $Comp) {
echo $Comp['name']."
";;
}
result
c
change management
coaching
SimpleXmlElement::xpath()
always returns an array of SimpleXMLElement
objects. Even if the expressions returns a list of attribute nodes. In this case the attribute nodes get converted into SimpleXMLElement
instances. If you cast them to strings you will get the attribute value:
$element = new SimpleXMLElement($xml);
foreach ($element->xpath('//Competency/@name') as $child) {
var_dump(get_class($child), (string)$child);
}
Output:
string(16) "SimpleXMLElement"
string(1) "c"
string(16) "SimpleXMLElement"
string(17) "change management"
string(16) "SimpleXMLElement"
string(8) "coaching"
If this is to much magic, you need to use DOM. It's more predictable and explicit:
$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"