get the latest node value in xml file using php code
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.
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:
<id>
nodes with xpath
, 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
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. :-)
链接地址: http://www.djcxy.com/p/29840.html上一篇: 在PHP中更改xml文件的编码