2012-02-23 68 views
0

我浪費了大量時間試圖編輯和刪除xml文件中的特定節點。現在我成功刪除了該節點,但是當我嘗試編輯節點時,它只會更新最後一個節點。如何使用PHP編輯和刪除XML中的特定節點

我的XML文件如下:

<?xml version="1.0"?> 
    <reviews> 
    <product name="NokiaN9White"> 
     <user name="testuser" id="02232012062451"> 
     <username>[email protected]</username> 
     <date_post>23-02-2012</date_post> 
     <date_update>23-02-2012</date_update> 
     <review>Hello dear.</review> 
     </user> 
     <user name="testuser" id="02232012062521"> 
     <username>[email protected]</username> 
     <date_post>23-02-2012</date_post> 
     <date_update>23-02-2012</date_update> 
     <review>Mrr</review> 
     </user> 
     <user name="testuser" id="02232012062523"> 
     <username>[email protected]</username> 
     <date_post>23-02-2012</date_post> 
     <date_update>23-02-2012</date_update> 
     <review>adfasdf</review> 
     </user> 
    </product> 
</reviews> 

我來編輯這些數據的代碼是:

$xmlDoc = new DOMDocument(); 
$xmlDoc->load(dirname(__FILE__)."/reviews.xml"); 

$products = $xmlDoc->getElementsByTagName("product"); 
    foreach($products as $product) 
    { 
     $prdoductN = $product->getAttribute("name"); 
     if($prdoductN == $product_name){ 

      $users = $product->getElementsByTagName("user"); 

      $userR = get_userName($_SESSION['userName']); 
      foreach($users as $user){ 
       $userName = $user->getAttribute("name"); 
       $review_id = $user->getAttribute("id"); 

       if($userName == $userR && $review_id == $r_id){ 

        $current_date = date('d-m-Y'); 

        $eventN = $user->getElementsByTagName("date_update"); 
        $eventN->item(0)->nodeValue = $current_date; 

        $eventC = $user->getElementsByTagName("review"); 
        $eventC->item(0)->nodeValue = $comments; 

       } 
      } 

      $xmlDoc->formatOutput = true; 
      //$xmlDoc->saveXML(); // This will return the XML as a string 
      $xmlDoc->save(dirname(__FILE__)."/reviews.xml"); 
     } 
    } 

回答

0

您可以使用左巴提供的PHP擴展來實現你的例子:

declare namespace a = "http://www.zorba-xquery.com/annotations"; 

declare variable $doc := <reviews>...</reviews>; 

declare %a:sequential function local:remove-user(
    $doc as element(reviews), $name as xs:string, $id as xs:string 
) as element(reviews) 
{ 
    delete node $doc//user[@name = $name and @id = $id]; 
    $doc 
}; 

local:remove-user($doc, "testuser", "02232012062523") 

你可以試試你的例子http://www.zorba-xquery.com/html/demo#2awjZFgWFxoIi7uE2J4HgwUQUuA=

說明如何使用PHP安裝的XQuery擴展可在http://www.zorba-xquery.com/html/entry/2011/12/27/PHP_Meets_XQuery

+0

謝謝你,但是這還需要安裝其他文件。(即:某些.DLL .SA)。我只需要通過只有PHP做到這一點。 – 2012-02-23 10:40:06