一尘不染

如何使用SimpleXmlElement编写CDATA?

php

我有以下代码来创建和更新xml文件:

<?php
$xmlFile    = 'config.xml';
$xml        = new SimpleXmlElement('<site/>');
$xml->title = 'Site Title';
$xml->title->addAttribute('lang', 'en');
$xml->saveXML($xmlFile);
?>

这将生成以下xml文件:

<?xml version="1.0"?>
<site>
  <title lang="en">Site Title</title>
</site>

问题是:是否可以使用此方法/技术添加CDATA以在下面创建xml代码?

<?xml version="1.0"?>
<site>
  <title lang="en"><![CDATA[Site Title]]></title>
</site>

阅读 402

收藏
2020-05-29

共1个答案

一尘不染

得到它了!我从这个很棒的解决方案改编了代码:

<?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>
2020-05-29