>  기사  >  php教程  >  php simpleXML添加CDATA格式数据

php simpleXML添加CDATA格式数据

WBOY
WBOY원래의
2016-05-25 16:42:12862검색

我们知道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);


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.