如何使用PHP删除和编辑特定的xml节点?

时间:2013-07-08 10:05:14

标签: php xml edit

我正在练习XML和PHP。我无法找到如何删除整个xml节点。这是我的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>

以下是我遇到问题的两个函数的代码,delete()和edit()

<?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文件中的一个。

1 个答案:

答案 0 :(得分: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