Hi ,
I have an exctiing xml file which has id's 1 - 20 when I create a new xml file I need it to add the ID to the file how can I do this ?
I know how you would do it with SQL but not with xml
please help
Hi ,
I have an exctiing xml file which has id's 1 - 20 when I create a new xml file I need it to add the ID to the file how can I do this ?
I know how you would do it with SQL but not with xml
please help
Find the highest ID in your existing file, using some XPath query and php code.
$ids = $xml->xpath("element/id"); // or something that fits your XML document
asort($ids); // or use some other sorting algorithm
$highest_id = end($ids);
I am not very knowledgeable about xpath queries, so there might be some trick to sort it during the query I suppose, but someone else will probably point this out if this example can be optimised.
Next create your new XML document and add the highest ID to it.
if your xml is already ordered from lowest to highest, you can do this xpath query:
$res = $doc->xpath('/list/a[not(@id <= preceding-sibling::a/@id) and ' .
'not(@id <= following-sibling::a/@id)]/@id');
$nextId = is_array($res) && count($res) ? (intval($res[0]->id) + 1) : 0;
otherwise, you can find the max id like so (assuming id is an attribute):
$xml = '<list><a id="1" /><a id="2" /><a id="3" /></list>';
$doc = simplexml_load_string($xml);
$max = -1;
foreach ($doc->xpath('/list/a/@id') as $el) {
$i = intval($el->id); if ($i > $max) $max = $i;
}
echo "Max: $max";
the above prints "3", so your new id is 4
or use Veger's solution which will also work