XML xpath属性值

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> 
douduan1953
douduan1953 我使用DOMDocument解析器,它有更多的选项,更容易使用。如果你喜欢xpath,请阅读:stackoverflow.com/questions/4492674/xml-xpath-print-element
5 年多之前 回复

2个回答

foreach ($xml->Competency as $Comp) {
   echo $Comp['name']."
";;
   }

result

c
change management
coaching

SimpleXmlElement::xpath() always returns an array of SimpleXMLElementobjects. 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"
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐