Get attribute value from different elements (simpleXML)

时间:2015-09-01 22:17:01

标签: php xml simplexml

I would like to know if there is a way to get XML attribute values from different elements by using SimpleXML?

Considering the following XML:

<element1>
    <sub-element1 color="red">Content</sub-element1>
</element1>
<element2>
    <sub-element2 color="blue">Content</sub-element>
</element2>

I would like to parse this xml to get :

red
blue

Please note that the "color" attribute may exist in more than 30 different elements so I don't want to select the attribute element by element.

Thank you for your help!

Damien

1 个答案:

答案 0 :(得分:0)

您可以使用以下XPath表达式获取XML文档中任何元素的color属性:

//*/@color

请注意,您可以使用*引用任何名称的元素,并使用@*在XPath中引用任何名称的属性

eval.in demo

$string = <<<XML
<root>
    <element1>
        <sub-element1 color="red">Content</sub-element1>
    </element1>
    <element2>
        <sub-element2 color="blue">Content</sub-element2>
    </element2>
</root>
XML;
$xml = new SimpleXMLElement($string);
$colors = $xml->xpath("//*/@color");
foreach($colors as $color){
    echo $color ."\r\n";
}

输出

red
blue