Access value through parent attribute [duplicate]

匆匆过客 提交于 2019-12-12 01:30:00

问题


I am looking to get the value A-1 through xpath based on a passed attribue.

I have passed the index attribute of the unit through php from a previous page and am accessing it by global GET:

$value = intval($_GET['index']);

the xml:

<UNIT index='1'>
     <ID>A-1</ID>
     <MANUFACTURER>testing inc.</MANUFACTURER>
</UNIT>
<UNIT index='2'>
     <ID>A-2</ID>
     <MANUFACTURER>testing inc.</MANUFACTURER>
</UNIT>

I'm trying to echo it out using:

$xml = new SimpleXMLElement('demo.xml',NULL,true);

echo $xml->UNIT[$value]->ID;

I know i'm getting the "1" that I need passed through because I echo'd $value to check, but its giving me the ID of A-2, which would be the xml index number (starting from 0) - not my attribute index number.


回答1:


You can use the SimpleXMLElement::xpath method to query for the specific UNIT that you want with an XPath query like //UNIT[@index=2].

$value = intval($_GET['index']);
$xml   = new SimpleXMLElement('demo.xml',NULL,true);
$units = $xml->xpath("//UNIT[@index=$value]"); // xpath returns an array
if (isset($units[0])) {
    echo $units[0]->ID;
} else {
    echo "No unit with index $value";
}



回答2:


Use:

//UNIT[@index=$value]/ID



来源:https://stackoverflow.com/questions/2974114/access-value-through-parent-attribute

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