2012-04-17 109 views
1

我的XML看起來像這樣:PHP XML刪除元素

<?xml version="1.0" encoding="utf-8" standalone="yes"?> 
<images> 
    <pic> 
     <image>54</image> 
     <descr>Image 1</descr> 
    </pic> 
    <pic> 
     <image>32</image> 
     <descr>Image 2</descr> 
    </pic> 
    <pic> 
     <image>47</image> 
     <descr>Image 3</descr> 
    </pic> 
</images> 

我想刪除一個元件,例如第二照片(圖像32)。使用此代碼,但它不起作用。

$xml = simplexml_load_file('../../images.xml'); 

$target = false; 
$i = 0; 
foreach ($xml->pic as $m) { 
    if ($m['image']=='32') { $target = $i; break; } 
    $i++; 
} 
if ($target !== false) {  //$target always be $false 
    unset($xml->pic[$target]); 
} 

echo $xml->savexml(); 

感謝您的任何建議。

回答

1

觀察

$m是反對不陣列,$m['image']應改爲$m->image

變化$target = false;噸Ø$target = 0 ;

$xml = simplexml_load_file ('1.xml'); 
$target = 0; 
$i = 0; 
foreach ($xml->pic as $m) { 
    if ($m->image == '32') { 
     $target = $i; 
     break; 
    } 
    $i ++; 
} 

if ($target !== false) { 
    unset ($xml->pic [$target]); 
} 
echo $xml->savexml(); 
+1

這不起作用。他對目標的原始測試很好 - 這段代碼會一直刪除第二個「pic」。 – 2012-04-17 22:45:11

+0

+1謝謝@Sam Dufel ..只是注意到對$ i的依賴性改變了我的腳本 – Baba 2012-04-17 22:47:54

0

嘗試創建一個新的XML對象,並只添加所需的數據並保存新對象。

0

您的測試是錯誤的

if ($target !== false) { 

應該

if ($target > 0) { 
+0

這是不正確 – 2012-04-17 22:43:00

+0

!==爲相同的值,型式試驗。 0永遠不會!== false(布爾和int)。 – 2012-04-17 22:46:43

+1

重讀他的代碼。他將目標初始化爲「false」,並在找到正確的索引時將其設置爲整數值。如果'target === false',則從未找到正確的索引。否則,目標已被設置爲他正在刪除的元素的索引(並且0是有效索引)。 – 2012-04-17 22:49:34