使用PHP DOMDocument替换XML节点的非文本

时间:2012-11-21 05:19:23

标签: php xml

我想替换XML节点的innertext,我的名为test.xml的XML文件是

<?xml version="1.0" encoding="utf-8"?>
<ads>
    <loop>no</loop>
    <item>
        <description>Description 1</description>
    </item>
    <item>
        <description>Text in item2</description>
    </item>
    <item>
        <description>Let play with this XML</description>
    </item>
</ads>

我想更改loopdescription标记的值, 它应该保存在test.xml中:

<?xml version="1.0" encoding="utf-8"?>
<ads>
    <loop>yes</loop>
    <item>
        <description>Description Changing Here</description>
    </item>
    <item>
        <description>Changing text in item2</description>
    </item>
    <item>
        <description>We will play later</description>
    </item>
</ads>

我在PHP中尝试过代码:

<?
    $file = "test.xml";
    $fp = fopen($file, "rb") or die("cannot open file");
    $str = fread($fp, filesize($file));
    $dom=new DOMDocument();
    $dom->formatOutput = true;
    $dom->preserveWhiteSpace = false;
    $dom->loadXML($str) or die("Error");
    //$dom->load("items.xml");

    $root=$dom->documentElement; // This can differ (I am not sure, it can be only documentElement or documentElement->firstChild or only firstChild)

    $loop=$root->getElementsByTagName('loop')->item(0);//->textContent;
    //echo $loop;
    if(trim($loop->textContent)=='no')
    {
        echo 'ok';
        $root->getElementsByTagName('loop')->item(0)->nodeValue ='yes';
    }
    echo "<xmp>NEW:\n". $dom->saveXML() ."</xmp>";
?>

我只尝试使用loop代码。我不知道如何替换nodevalue中的description tag。 当我运行此页面时,它显示如下输出:

ok
NEW:
<?xml version="1.0" encoding="utf-8"?>
<ads>
    <loop>yes</loop>
    <item>
        <description>Description 1</description>
    </item>
    <item>
        <description>Changing text in item2</description>
    </item>
    <item>
        <description>Let play with this XML</description>
    </item>
</ads>

它在浏览器中提供值yes,但不以任何理由保存在test.xml中?

1 个答案:

答案 0 :(得分:1)

因此,由于您已创建DOMDocument,因此可以使用DOMXpath。或继续使用getElementsByTagName()

您可以这样做(但仅限于此背景下):

$descriptions = $root->getElementsByTagName('description');
foreach($descriptions as $nodeDesciption)
{
    $nodeDesciption->nodeValue ='Your custom value';
}