get the latest node value in xml file using php code -


i new wih xml file .. want latest node id value of xml file using php script , calculate when add 1 more node xml file .. ..<id>2</id> , next node <id>3</id> after adding...

suppose have xml file below:

<?xml version="1.0" encoding="utf-8"?> <books>  <book>   <id>1</id>   <name>java</name>  </book>  <book>   <id>2</id>   <name>c++</name>  </book> </books> 

can guide me which's way solve php script ...thank advance .

now had found solution

//auto id        $doc = new domdocument();       libxml_use_internal_errors(true);       $doc->loadxml(file_get_contents ('../books.xml')); // loads xml        $xpath = new domxpath($doc); ///create object xpath        $nlist = $xpath->query("//books/book/id");       $count = $nlist->length; //count number of node        $id = $nlist->item($count-1)->nodevalue;      $id+=1;        echo $id ; //end auto id  

so, can increment 1 value $id when inserting new node.

keep simple simplexml:

$xml = simplexml_load_string($x); // assuming xml in $x $maxid = max(array_map('intval',$xml->xpath("//id"))); 

what does:

  • get array of <id> nodes xpath,
  • transform each value integer max() can job.

now add new <book> $maxid + 1:

$book = $xml->addchild('book'); $book->addchild('id',$maxid + 1); $book->addchild('name','php'); 

see in action: http://codepad.viper-7.com/5jextj


Comments