1

I want to get the value of last id in item element. For example, in the xml below, I want to get value 2 and increment one for the id for next item entered. So if the next item is entered, the id will automatically be 3 and so on. Tried couple ways but I still cant get it to work. Any suggestions? items.xml

<?xml version="1.0"?>
<items>
<item>
    <id>1</id>
    <name>N95</name>
    <desc>Nokia</desc>
    <price>299</price>
    <quantity>11</quantity>
</item>
<item>
    <id>2</id>
    <name>S4</name>
    <desc>Samsung</desc>
    <price>500</price>
    <quantity>50</quantity>
</item>
</items>

php file

$x = file_get_contents('../../data/items.xml');
$root = $x->documentElement; //root element(items)
$lastId = $root->lastChild->firstChild->firstChild->nodeValue; //navigate to get the value of last item id
$newItemId = $lastId + 1;
bisonsausage
  • 71
  • 3
  • 12

1 Answers1

1

You could use SimpleXML with xpath to target the last element. Example:

$xml = simplexml_load_file('../../data/items.xml');
$last_item = $xml->xpath('//item[last()]');
$last_id = (int) $last_item[0]->id;
$newItemId = $last_id + 1;
echo $newItemId; // 3

Or simple as this:

$count = count($xml);
$last_item = $xml->item[$count-1];
$last_id = (int) $last_item->id;
$newItemId = $last_id + 1;
Kevin
  • 41,694
  • 12
  • 53
  • 70
  • Thanks for all your help Ghost, really appreciate it. I haven't learn xpath at the moment. From all your previous examples, I assume that we can navigate through xml file easier compared to childNode, am I right? @Ghost – bisonsausage Oct 19 '14 at 15:42
  • @bisonsausage yes and you can target much more specific elements that you want, i'm sure sooner or later you'll get the hang of if, its somewhat like using jquery with selectors, etc. im glad this helped – Kevin Oct 19 '14 at 15:52