©
本文檔使用 php中文網手册 發布
(PHP 5, PHP 7)
DOMDocument::createCDATASection — Create new cdata node
$data
)This function creates a new instance of class DOMCDATASection. 此节点出现在文档中,除非是用诸如 DOMNode->appendChild() 等函数来将其插入。
data
The content of the cdata.
The new DOMCDATASection or FALSE
if an error occurred.
[#1] Marc info[at]braincast.nl [2011-03-08 01:55:28]
Here's some code that takes an associative array and prints it asXML() but creates CDATA sections for each string
<?php
<{$root_element_name}></{$root_element_name}>");
class SimpleXMLExtended extends SimpleXMLElement{
public function addCData($string){
$dom = dom_import_simplexml($this);
$cdata = $dom->ownerDocument->createCDATASection($string);
$dom->appendChild($cdata);
}
}
function assocArrayToXML($root_element_name,$ar){
$xml = new SimpleXMLExtended("<?xml version=\"1.0\"?>
$f = create_function('$f,$c,$a','
foreach($a as $k=>$v) {
if(is_array($v)) {
if (!is_numeric($k))$ch=$c->addChild($k);
else $ch = $c->addChild(substr($c->getName(),0,-1));
$f($f,$ch,$v);
} else {
if (is_numeric($v)){ $c->addChild($k, $v);
}else{$n = $c->addChild($k); $n->addCData($v);}
}
}');
$f($f,$xml,$ar);
return $xml->asXML();
}
$result = array("title"=>"CDATA Sample");
$result['items'] = array();
$result['items'][] = array('title'=>'Some string', 'number' => 1);
$result['items'][] = array('title'=>'Some string', 'number' => 2);
$result['items'][] = array('title'=>'Some string', 'number' => 3);
echo assocArrayToXML('result',$result);
?>
The is_numeric check could be changed by a more elaborate regular expression to check if the string is actually xml unsafe but this worked for me.
[#2] jesdisciple dot FOO at gmail dot BAR dot com [2010-07-08 04:44:18]
If you would like to refer to the documentation for the class of the returned object, see http://www.php.net/manual/en/class.domcharacterdata.php
[#3] info at troptoek dot com [2008-03-24 21:40:09]
A common issue seems to be adding javascript to CDATA and the browser throwing a javascript error. To ensure the javascript works use the following code when adding CDATA:
<?php
function appendCdata($appendToNode, $text)
{
if (strtolower($appendToNode->nodeName) == 'script') { // Javascript hack
$cm = $appendToNode->ownerDocument->createTextNode("\n//");
$ct = $appendToNode->ownerDocument->createCDATASection("\n" . $text . "\n//");
$appendToNode->appendChild($cm);
$appendToNode->appendChild($ct);
} else { // Normal CDATA node
$ct = $appendToNode->ownerDocument->createCDATASection($text);
$appendToNode->appendChild($ct);
}
}
?>
The result should be:
<script type="text/javascript">
//<![CDATA[
function someJsText() {
document.write('Some js with <a href="#">HTML</a> content');
}
//]]></script>
[#4] loathsome [2007-08-04 14:28:02]
Here's a function that will create a CDATA-section around a string coming from SimpleXML.
<?php
function sxml_cdata($path, $string){
$dom = dom_import_simplexml($path);
$cdata = $dom->ownerDocument->createCDATASection($string);
$dom->appendChild($cdata);
}
?>