1

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

So that's almost what I need. But I need to extract the value contained within the element itself. So this2 should be value
$value = current($myXml->xpath("/sub[@name=this1]"); This will only work nicely if the query returns only a single element, the rest would be lost.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.