简体   繁体   中英

PHP XML How to extract the element where name= using simpleXML

I have an XML file I need to extract only certain elements from. And at some point the XML file could be updated and completely change the order which the elements appear in - but the elements contain a name= setting.

<element>
 <sub name='this1'>value</sub>
 <sub name='this2'>value</sub>
 <sub name='this3'>value</sub>
 <sub name='this4'>value</sub>     
</element>

I need to extract the values say for this2 and this4.

But at some stage, new sub elements may be added, changing the order. So I can't use:

$xml->element->sub[2]

Example below:

<element>
 <sub name='this0'>value</sub>
 <sub name='this1'>value</sub>
 <sub name='this2'>value</sub>
 <sub name='this3'>value</sub>     
 <sub name='this4'>value</sub>    
</element>

So sub[2] would then become this1 instead of this2.

What you want is a XPath query, eg $myXml->xpath("/sub[@name=this1]") . Read more about Xpath here http://php.net/manual/de/simplexmlelement.xpath.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM