php simpleXML添加CDATA格式数据

作者:袖梨 2022-06-24

代码

 代码如下 复制代码

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

相关文章

精彩推荐