2014-10-19 68 views
1

我想獲取item元素中最後一個id的值。例如,在下面的xml中,我想獲得值2併爲輸入的下一個項目添加一個id。所以如果輸入下一個項目,id將自動爲3,依此類推。嘗試了幾種方法,但我仍然無法實現它的工作。有什麼建議麼? items.xml如何獲取xml中的最後一個節點值

<?xml version="1.0"?> 
<items> 
<item> 
    <id>1</id> 
    <name>N95</name> 
    <desc>Nokia</desc> 
    <price>299</price> 
    <quantity>11</quantity> 
</item> 
<item> 
    <id>2</id> 
    <name>S4</name> 
    <desc>Samsung</desc> 
    <price>500</price> 
    <quantity>50</quantity> 
</item> 
</items> 

php文件

$x = file_get_contents('../../data/items.xml'); 
$root = $x->documentElement; //root element(items) 
$lastId = $root->lastChild->firstChild->firstChild->nodeValue; //navigate to get the value of last item id 
$newItemId = $lastId + 1; 

回答

1

你可以使用SimpleXML使用XPath目標的最後一個元素。例如:

$xml = simplexml_load_file('../../data/items.xml'); 
$last_item = $xml->xpath('//item[last()]'); 
$last_id = (int) $last_item[0]->id; 
$newItemId = $last_id + 1; 
echo $newItemId; // 3 

或簡單的,因爲這:

$count = count($xml); 
$last_item = $xml->item[$count-1]; 
$last_id = (int) $last_item->id; 
$newItemId = $last_id + 1; 
+0

感謝您的所有幫助鬼,真的很感激。我目前還沒有學習xpath。從以前的所有示例中,我認爲我們可以通過xml文件輕鬆導航,與childNode相比,我是對嗎? @Ghost – bisonsausage 2014-10-19 15:42:06

+0

@bisonsausage是的,你可以針對你想要的更具體的元素,我相信遲早你會得到如果,它有點像使用jQuery與選擇器等。我很高興這有助於 – Ghost 2014-10-19 15:52:09