PHP and XML - Set unique ids in document -
i have script example:
while (count($xml->xpath('*[@id="' . $id . '"]/@id')) > 0) { $id = 'example_' . ++$x; } but if check 1.000 childrens in element, must wait more hour response.
how quicker check if id exists?
thank's in advance tip!
get unique id grabbing highest id , add 1 it.
didn't provide xml, assume following example:
<elements> <element id="example_1" /> <element id="example_5" /> <element id="example_27" /> </elements> this code (php >= 5.3 inline function):
$xml = simplexml_load_string($x); // assume xml in $x $ids = $xml->xpath("//element/@id"); $newid = max(array_map( function($a) { list(, $id) = explode("_", $a); return intval($id); } , $ids)) + 1; $newid = "example_$newid"; echo $newid; output:
example_28 see working: http://codepad.viper-7.com/sfvf7v
comments:
1. xpathexpression in line 2 builds array $ids of ids in xml
2. need separate example number @ _ , change number int in order perform max(), done array_map()calling inline function
3. within function, use list() grab number part of string seperated explode() , return int
Comments
Post a Comment