Can I use SimpleXML & Xpath to directly select an Elements Attribute?

拟墨画扇 提交于 2019-12-19 08:52:04

问题


i.e. - i want to return a string "yellow" using something like xpath expression "//banana/@color" and the following example xml...

<fruits>
 <kiwi color="green" texture="hairy"/>
 <banana color="yellow" texture="waxy"/>
</fruits>


$fruits = simplexml_load_string(
'<fruits>
 <kiwi color="green" texture="hairy"/>
 <banana color="yellow" texture="waxy"/>
</fruits>');

print_r($fruits->xpath('//banana/@color'));

produces

Array
(
    [0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [color] => yellow
                )

        )

)

whereas i would prefer something like...

Array
(
    [0] => SimpleXMLElement Object
        (
            [0] => yellow
        )

)

...so that i don't need to write a special case into the application i'm writing.

thanks very much! :)


回答1:


I just gave your test a shot because i was curious and I found that it does actually produce the string value yellow when converted to string.

$fruits = simplexml_load_string(
'<fruits>
 <kiwi color="green" texture="hairy"/>
 <banana color="yellow" texture="waxy"/>
</fruits>');

$found = $fruits->xpath('//banana/@color');
echo $found[0];

It would seem this is just how SimpleXmlElement attribute nodes are represented. So you can use this as (string) $found[0] if you are not printing/echoing it directly.

Of course if your depending on the value remaining a SimpleXMLElement then that could be an issue I suppose. But i would think just remembering to cast as string when you go to use the node later would still be doable.

IF you really need a detailed interface for Nodes that supports an Attribute as a node then you may want to just switch to DOMDocument. You code will get more verbose, but the implementation is more clear.



来源:https://stackoverflow.com/questions/4045600/can-i-use-simplexml-xpath-to-directly-select-an-elements-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!