使用SimpleXmlElement编写CDATA数据

2,570次阅读

共计 607 个字符,预计需要花费 2 分钟才能阅读完成。

<?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 version="1.0"?>
<site>
  <title lang="en"><![CDATA[Site Title]]></title>
</site>

正文完
 
Blood.Cold
版权声明:本站原创文章,由 Blood.Cold 2019-06-04发表,共计607字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。