XML将内容替换为其他内容


XML replace content to other

我有这个脚本:

$dom=new DOMDocument();
$xml='../assets/local.xml';
$dom->load($xml);
$cdata=$dom->createCDATASection('95.55.4.2');
foreach ($dom->getElementsByTagName('connection') as $item) {
    $item->getElementsByTagName('host')->item(0)->appendChild($cdata);
}
$dom->save($xml);

我的xml是:

<connection>
<host>localhost</host>
</connection>

我需要用CData将"localhost"更改为"95.55.4.2"。我试着用这张纸条,但他错了。。。这就是结果:

<connection>
<host>95.55.4.2localhost</host>
</connection>

任何人都可以帮我

谢谢!!

您可以使用nodeValue直接设置节点值:

$dom=new DOMDocument();
$xml='../assets/local.xml';
$dom->load($xml);
# access the element directly: it's the first "host" node in the doc:
$dom->getElementsByTagName('host')->item(0)->nodeValue = '95.55.4.2';
$dom->save($xml);

使用appendChild会将CDATA节点添加到现有的子节点中,这就是为什么您将获得新旧字符串的组合。