如何使用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:
<?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 version="1.0"?>
<site>
<title lang="en"><![CDATA[Site Title]]></title>
</site>
谢谢您 Petah
这篇关于如何使用SimpleXmlElement编写CDATA?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文