php - How to get the last node value in xml -
i want value of lastly id in item element. example, in xml below, want value 2 , increment 1 id next item entered. if next item entered, id automatically 3 , on. tried couple ways still cant work. 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 value of lastly item id $newitemid = $lastid + 1;
you utilize simplexml xpath target lastly 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 this:
$count = count($xml); $last_item = $xml->item[$count-1]; $last_id = (int) $last_item->id; $newitemid = $last_id + 1; php xml simplexml
No comments:
Post a Comment