0

I am new wih xml file .. I want to get the latest node id value of xml file using php script and calculate it when I add one more node to this xml file .. something like this ..<id>2</id> and the next node will be <id>3</id> after adding...

suppose that i have an xml file like 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 you guide me which's way to solve this with php script ...thank for advance .

now i had found my solution

//auto id 
      $doc = new DOMDocument();
      libxml_use_internal_errors(true);
      $doc->loadXML(file_get_contents ('../books.xml')); // loads your 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, you can get the increment one value to $id when inserting new node.

phireak
  • 45
  • 2
  • 8

2 Answers2

0

Check this link:

http://www.phpeveryday.com/articles/PHP-XML-Adding-XML-Nodes-P414.html

It has an example almost exactly what you need - its even a book example. Just be aware that you need to autoincrement the id and not hard code it like on the example.

Its really self explanatory.

And heres a nice reference read for you:

http://pt1.php.net/manual/en/simplexmlelement.addchild.php

Hope it helped. :-)

blahblah
  • 96
  • 1
  • 4
0

keep it simple with simplexml:

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

What it does:

  • get an array of all <id> nodes with xpath,
  • transform each value to integer so that max() can do its job.

Now add a new <book> with $maxid + 1:

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

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

michi
  • 6,565
  • 4
  • 33
  • 56