[英]Replacing innertext of XML node using PHP DOMDocument
I want to replace innertext of a XML node my XML file named test.xml
is 我想替换XML节点的内部文本,名为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>
I want to change the value of loop
and description
tag both, and it should be saved in test.xml
like: 我想同时更改loop
和description
标签的值,并且应将其保存在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>
I tried code in PHP: 我在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>";
?>
I tried only for loop
tag.I don't know how to replace nodevalue
in description tag
. 我只尝试了loop
description tag
。我不知道如何替换description tag
nodevalue
。 When I run this page it shows output like: 当我运行此页面时,它显示如下输出:
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>
It gives the value yes
in browser but don't save it in test.xml
any reason? 它在浏览器中给出值yes
,但是由于任何原因不将其保存在test.xml
?
So, since you have created DOMDocument
you can use DOMXpath . 因此,由于创建了DOMDocument
,因此可以使用DOMXpath 。 Or keep using getElementsByTagName()
或继续使用getElementsByTagName()
You could do this (but only in that context): 您可以这样做(但仅在这种情况下):
$descriptions = $root->getElementsByTagName('description');
foreach($descriptions as $nodeDesciption)
{
$nodeDesciption->nodeValue ='Your custom value';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.