如何使用 SimpleXmlElement 编写 CDATA? [英] How to write CDATA using SimpleXmlElement?
本文介绍了如何使用 SimpleXmlElement 编写 CDATA?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个代码来创建和更新 xml 文件:
I have this code to create and update xml file:
<?php
$xmlFile = 'config.xml';
$xml = new SimpleXmlElement('<site/>');
$xml->title = 'Site Title';
$xml->title->addAttribute('lang', 'en');
$xml->saveXML($xmlFile);
?>
这会生成以下 xml 文件:
This generates the following xml file:
<?xml version="1.0"?>
<site>
<title lang="en">Site Title</title>
</site>
问题是:有没有办法用这种方法/技术添加CDATA来创建下面的xml代码?
The question is: is there a way to add CDATA with this method/technique to create xml code below?
<?xml version="1.0"?>
<site>
<title lang="en"><![CDATA[Site Title]]></title>
</site>
推荐答案
Got it! I adapted the code from this great solution (archived version):
<?php
// http://coffeerings.posterous.com/php-simplexml-and-cdata
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('<site/>');
$xml = new SimpleXMLExtended('<site/>');
$xml->title = NULL; // VERY IMPORTANT! We need a node where to append
$xml->title->addCData('Site Title');
$xml->title->addAttribute('lang', 'en');
$xml->saveXML($xmlFile);
?>
生成的 XML 文件:
XML file generated:
<?xml version="1.0"?>
<site>
<title lang="en"><![CDATA[Site Title]]></title>
</site>
谢谢佩塔
这篇关于如何使用 SimpleXmlElement 编写 CDATA?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文