Reputation: 63
I have this XML data:
<root>
<child>child1</child>
<child>child2</child>
<child>child3</child>
</root>
I can parse it with PHP:
$xml = simplexml_load_string($string);
I want to skip the first 2 children and get this result:
<root>
<child>child3</child>
</root>
Thank you
Upvotes: 0
Views: 78
Reputation: 197832
If you ask in your question about removing all <child>
elements until there is only one left, you can do that with a simple while
-loop:
<?php
/**
* skip 2 element in xml code with php
*
* @link https://stackoverflow.com/q/31879798/367456
*/
$string = <<<XML
<root>
<child>child1</child>
<child>child2</child>
<child>child3</child>
</root>
XML;
$xml = simplexml_load_string($string);
$child = $xml->child;
while ($child->count() > 1) {
unset($child[0]);
}
$xml->asXML('php://output');
The output is (also: online-demo):
<?xml version="1.0"?>
<root>
<child>child3</child>
</root>
if you're only concerned to get the last element, use an xpath query as it has been suggested in the other answer. Do not even consider to use the array mish-mash of json encode decode - will only break the data you need to retain in the end.
Upvotes: 1
Reputation: 6406
You can query the element you're interested in with an Xpath query:
$xml = new SimpleXMLElement($string);
$last = $xml->xpath("child[last()]")[0];
Inspired by PHP: How to access the last element in a XML file.
Upvotes: 2