2013-07-08 111 views
0

我正在練習XML和PHP。我找不到如何刪除整個XML節點。下面是我的XML:如何使用PHP刪除和編輯特定的xml節點?

<?xml version="1.0" encoding="UTF-8"?> 
<items> 
<playlist_name>Channel List</playlist_name> 
<category> 
<category_id>1</category_id> 
<category_title>HD</category_title> 
</category> 
<channel> 
<title>VTC HD1</title> 
<stream_url><![CDATA[http://203.162.16.22:80/lives/origin01/vtchd1.isml/vtchd1.m3u8]]></stream_url> 
<logo_30x30>vtchd1.jpg</logo_30x30> 
<category_id>1</category_id> 
</channel> 
<channel> 
<title>VTC HD2</title> 
<stream_url><![CDATA[http://203.162.16.22:80/lives/origin01/vtchd2.isml/vtchd2.m3u8]]></stream_url> 
<logo_30x30>vtchd2.jpg</logo_30x30> 
<category_id>1</category_id> 
</channel> 
</items> 

,這裏是)))兩大功能,我有問題,刪除(和編輯(

<?php 

function delete_channel() 
{ 
    $file = "nStream.xml"; 
    $fp = fopen($file, "rb") or die("cannot open file"); 
    $str = fread($fp, filesize($file)); 

    $xml = new DOMDocument(); 
    $xml->formatOutput = true; 
    $xml->preserveWhiteSpace = false; 
    $xml->loadXML($str) or die("Error"); 

    // original 
//  echo "<xmp>OLD:\n". $xml->saveXML() ."</xmp>"; 

    // get document element 
    $root = $xml->documentElement; 
    $fnode = $root->firstChild; 

    //get a node 
    $ori = $fnode->childNodes->item(0); 

    // remove 
    $fnode->removeChild($ori); 

//  echo "<xmp>NEW:\n". $xml->saveXML() ."</xmp>"; 
} 

function edit_channel() 
{ 
    echo 'Go Edit'; 
} 

對於delete_channel(的代碼,沒有被刪除時我運行該功能。我希望每次使用該函數時,都會刪除xml文件中的一個。

+0

喜哈哈先生,究竟是不是工作? – michi

+0

這是「函數delete_channel()」和「函數edit_channel()」 –

+0

好吧,什麼不工作?你會得到什麼?錯誤?請具體說明。 – michi

回答

0

刪除<channel>simplexml

$xml = simplexml_load_file($filename); 

// select the channel to be deleted by title 
$channel = $xml->xpath("//channel[title='VTC HD2']"); 

// delete it! 
unset($channel[0][0]); 

// save it 
$xml->asXML($filename); 

看到它的工作:https://eval.in/37084