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.

4
  • largest id in the xml? Commented May 6, 2013 at 3:39
  • no .. i want to get the latest node id in this xml file only suppose that .. latest id node value = 2 and when i add more node the id of the new node id is 3 Commented May 6, 2013 at 3:44
  • so you want to add more nodes in books and auto increment the id? Commented May 6, 2013 at 3:46
  • yes . this is what i want . how to do it . please help me thank Commented May 6, 2013 at 3:49

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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. :-)

1 Comment

it's not the right solution for me . anyway thank you for your time try answer my problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.