开发者

how to get simpleXML to create an ID

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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜