Home  >  Article  >  php教程  >  php simpleXML添加CDATA格式数据

php simpleXML添加CDATA格式数据

WBOY
WBOYOriginal
2016-05-25 16:42:12904browse

我们知道php中的simpleXML没办法直接很方便的添加CDATA格式的数据,这样对我们操作时会有一定的问题,下面我来给各位同学介绍php simpleXML添加CDATA格式数据一种办法,php实例代码如下:

<?php 
/** 
* to show <title><![CDATA[Site Title]]></title>   instead of <title>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    = &#39;config.xml&#39;; 
// instead of $xml = new SimpleXMLElement(&#39;<sites/>&#39;); 
$xml = new SimpleXMLExtended(&#39;<sites/>&#39;); 
$site = $xml->addChild(&#39;site&#39;); 
// instead of $site->addChild(&#39;site&#39;, &#39;Site Title&#39;); 
$site->title = NULL; // VERY IMPORTANT! We need a node where to append 
$site->title->addCData(&#39;Site Title&#39;); 
$site->title->addAttribute(&#39;lang&#39;, &#39;en&#39;); 
$xml->asXML($xmlFile);


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn