2010-01-19 73 views

回答

1

如果XML已經從最低到最高排序,你可以這樣做XPath查詢:

$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; 

否則,你可以找到最大的id像這樣(假設ID是一個屬性):

$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"; 

上面打印 「3」,因此新的id是4

或使用Veger's solution這也將工作

0

查找現有文件中的最高ID,使用一些XPath查詢和PHP代碼。

$ids = $xml->xpath("element/id"); // or something that fits your XML document 
asort($ids);      // or use some other sorting algorithm 
$highest_id = end($ids); 

我不是XPath查詢非常熟悉,所以可能有一些竅門,我想在查詢過程中對它進行排序,但別人可能會指出這一點,如果這個例子可以優化。

接下來創建您的新XML文檔併爲其添加最高ID。

相關問題