php - XML count elements, If id exists increment by one -


what trying count elements under root element. check if 1 id on same level has id value. when occurs needs increment one.

the code

public function _generate_id() {     $id = 0;     $xpath = new domxpath($this->_dom);     do{         $id++;     } while($xpath->query("/*/*[@id=$id]"));      return $id; } 

example xml

<?xml version="1.0"?> <catalog>     <book id="0">         <author>gambardella, matthew</author>         <title>xml developer's guide</title>         <genre>computer</genre>         <price>44.95</price>         <publish_date>2000-10-01</publish_date>         <description>an in-depth @ creating applications             xml.</description>     </book>     <book id="1">         <author>ralls, kim</author>         <title>midnight rain</title>         <genre>fantasy</genre>         <price>5.95</price>         <publish_date>2000-12-16</publish_date>         <description>a former architect battles corporate zombies,             evil sorceress, , own childhood become queen             of world.</description>     </book> </catalog> 

you can use following xpath query maximum value of id attribute:

$result = $xpath->query('/*/*[not(../*/@id > @id)]/@id'); 

in function can return value incremented 1:

return intval($result->item(0)->nodevalue) + 1; 

update: can increment operation using xpath well. note domxpath::evaluate():

return $xpath->evaluate('/*/*[not(../*/@id > @id)]/@id + 1');                                                         |------- +1 in xpath 

this give 2 - double. suggest convert integer before returning result:

return (integer) $xpath->evaluate('/*/*[not(../*/@id > @id)]/@id + 1'); 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -