Search code examples
phpxmlsimplexml

Using SimpleXML to read the last tag ID


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>

Solution

  • 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