php使用simpleXML 添加 CDATA 格式数据
在做项目的时候,遇到一个需要处理xml文件的任务。把合作方传来的文件,加工下给引擎录入。
但是发现simpleXML没办法直接很方便的添加CDATA格式的数据,这样就会有很多问题。可能导致导出的xml格式错误。
找到了一个方法,分享给大家:
<?php
/**
* to show <title lang="en"><![CDATA[Site Title]]></title> instead of <title lang="en">Site Title</title>
*
*/
class SimpleXMLExtended extends SimpleXMLElement
{
public function addCData($cdata_text)
{
$node = dom_import_simplexml($this);
$no = $node->ownerDocument;
$node->appendChild($no->createCDATASection($cdata_text));
}
}
$xmlFile = 'config.xml';
// instead of $xml = new SimpleXMLElement('<sites/>');
$xml = new SimpleXMLExtended('<sites/>');
$site = $xml->addChild('site');
// instead of $site->addChild('site', 'Site Title');
$site->title = NULL; // VERY IMPORTANT! We need a node where to append
$site->title->addCData('Site Title');
$site->title->addAttribute('lang', 'en');
$xml->asXML($xmlFile);
?>











