0

我想替换我的 XML 文件名为的 XML 节点的内部test.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任何理由保存它?

4

1 回答 1

1

所以,既然你已经创建了,DOMDocument你就可以使用DOMXpath。或者继续使用getElementsByTagName()

您可以这样做(但仅在这种情况下):

$descriptions = $root->getElementsByTagName('description');
foreach($descriptions as $nodeDesciption)
{
    $nodeDesciption->nodeValue ='Your custom value';
}
于 2012-11-21T06:33:07.707 回答