1

I need to append new tags to a XML file and I can achieve this by using this code:

$file = 'xml/config.xml';

$xml = simplexml_load_file($file);

$galleries = $xml->examples;

$gallery = $galleries->addChild('Example');
$gallery->addChild('ExampleID', '123');
$gallery->addChild('ExampleText', 'this is text');
$gallery->addChild('ExampleDate', '23/12/1234');

$xml->asXML($file);

My problem is the ID.
Basically I need to get the last ExampleID and increment it to the new Example tag.

How can I achieve this?

Edit

This is the XML structure:

<Examples>
    <Example>
    <ExampleID>1</ExampleID>
    <ExampleText>this is text</ExampleText>
    ...
    </Example>
    <Example>
    <ExampleID>2</ExampleID>
    <ExampleText>this is the secont text</ExampleText>
    ...
    </Example>
</Examples>

2 Answers2

1

You can use XPATH. Here is the solution.

(string)$xml->xpath("//Examples/Example[not(../Example/ExampleID > ExampleID)]")[0]->ExampleID

Solution taken from http://php.net/manual/en/simplexmlelement.xpath.php & https://stackoverflow.com/a/3786761

Community
  • 1
  • 1
ARIF MAHMUD RANA
  • 5,026
  • 3
  • 31
  • 58
  • Can you explain the [0]? And also, I need to get the last example's ID, not the first. – Paulo Ferreira May 16 '16 at 09:35
  • You want the maximum example's ID right? Does it serve your purpose? `[0]` is for first 0 index – ARIF MAHMUD RANA May 16 '16 at 09:47
  • The Examples lenght is exactly what I need to get the last Example. How can I get it? – Paulo Ferreira May 16 '16 at 09:51
  • The Xpath expression return a node list of all `Example` elements with an `ExampeId` where its sibling nodes (and itself) does not contain a larger `ExampleId` value. In other words it returns the `Example` nodes with the largest value in the ExampleId child node. Because it is a node list the result is an array. It could be empty if here is no node. The `[0]` accesses the first element in the returned array. – ThW May 16 '16 at 13:23
0

You can use XPath last() to find the last <Example> element, and then return the corresponding <ExampleID> child :

//Example[last()]/ExampleID

Alternatively, you can find the maximum ExampleID, as mentioned in the other answer :

//ExampleID[not(. < //ExampleID)]

Demo : (eval.in)

$raw = <<<XML
<Examples>
    <Example>
    <ExampleID>1</ExampleID>
    <ExampleText>this is text</ExampleText>
    ...
    </Example>
    <Example>
    <ExampleID>2</ExampleID>
    <ExampleText>this is the secont text</ExampleText>
    ...
    </Example>
</Examples>
XML;
$xml = simplexml_load_string($raw);
$lastID = (string)$xml->xpath("//Example[last()]/ExampleID")[0];
echo $lastID;

Output :

2
har07
  • 88,338
  • 12
  • 84
  • 137