XML将内容替换为其他内容

时间:2014-10-28 11:38:57

标签: php xml

我有这个脚本:

$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>

任何可以帮助我的事

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用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节点添加到现有子节点,这就是您获得旧字符串和新字符串组合的原因。

相关问题