0

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

6
  • how did you create xml in php? Commented Aug 7, 2015 at 14:12
  • Have you tried parsers yet? stackoverflow.com/questions/3577641/… Commented Aug 7, 2015 at 14:14
  • i load this with $xml = simplexml_load_string(url here); Commented Aug 7, 2015 at 14:16
  • and after i use foreach Commented Aug 7, 2015 at 14:16
  • do you allways want to get the last child? Commented Aug 7, 2015 at 14:24

2 Answers 2

2

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.

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

Comments

1

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.

Comments

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.