2014-10-28 77 views
-2

我有此腳本: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> 

,我需要把 「localhost」 到 「95.55.4.2」 與CData的。我試試這個紙條,但他錯了...這就是結果:

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

任何可以幫助我,請

謝謝!

回答

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節點添加到現有的子節點,這就是爲什麼你得到新老串的組合。