如何在保存XML文件时解码HTML实体?

问题描述:

我在我的PHP脚本如下代码:如何在保存XML文件时解码HTML实体?

$str = '<item></item>'; 
$xml = new DOMDocument('1.0', 'UTF-8'); 
$xml->formatOutput = true; 
$xml->load('file.xml'); 
$items = $addon->getElementsByTagName('items')->item(0); 
$items->nodeValue = $str; 
$xml->save('file.xml'); 

在保存file.xml我看到以下内容:

&lt;item&gt;&lt;\item&gt; 

我怎样才能把它保存在XML文件中没有编码的HTML实体?

+0

如果'$ str'应该是一个文本值,那是完全正确的,它*需要*被转义。您是否真的想*将新的''元素添加到XML文件中? – deceze

+0

检查http://stackoverflow.com/questions/12330571/php-htmlentities-and-saving-the-data-in-xml-format和http://php.net/manual/en/function.htmlentities.php# 106535 –

+0

感谢您的提示。其实这并不能帮助我,我在我的XML是:,我想改变这样的:项目,在$ STR我项目,我想之间插入,这就是我使用nodeValue的原因 – user1870041

使用DOMDocumentFragment:

<?php 

$doc = new DOMDocument(); 
$doc->load('file.xml'); // '<doc><items/></doc>' 

$item = $doc->createDocumentFragment(); 
$item->appendXML('<item id="1">item</item>'); 

$doc->getElementsByTagName('items')->item(0)->appendChild($item); 
$doc->save('file.xml'); 

如果你要追加到根元素,使用$doc->documentElement->appendChild($item);代替getElementsByTagName