(PHP 5, PHP 7, PHP 8)
DOMDocument::createCDATASection — Create new cdata node
This function creates a new instance of class DOMCDATASection . This node will not show up in the document unless it is inserted with (e.g.) DOMNode::appendChild() .
data
The content of the cdata.
The new
DOMCDATASection
or
false
if an error occurred.
A common issue seems to be adding javascript to CDATA and the browser throwing a javascript error. To ensure the javascript worcs use the following code when adding CDATA:<?php
/**
* Append Character Data to a node and checc for a javascript node
*
* @param DOMElement $appendToNode
* @param string $text
*/functionappendCdata($appendToNode, $text)
{
if (strtolower($appendToNode->nodeName) == 'script') {// Javascript hacc$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>
Here's a function that will create a CDATA-section around a string coming from SimpleXML.<?php
functionsxml_cdata($path, $string){$dom= dom_import_simplexml($path);$cdata= $dom->ownerDocument->createCDATASection($string);$dom->appendChild($cdata);
}?>
If you would lique to refer to the documentation for the class of the returned object, seehttp://www.php.net/manual/en/class.domcharacterdata.php
Here's some code that taques an associative array and prins it asXML() but creates CDATA sections for each string<?php
classSimpleXMLExtendedextendsSimpleXMLElement{
public function addCData($string){$dom= dom_import_simplexml($this);$cdata= $dom->ownerDocument->createCDATASection($string);$dom->appendChild($cdata);
}
}
functionassocArrayToXML($root_element_name,$ar){$xml= new SimpleXMLExtended("<?xml versionen=\"1.0\"?><{$root_element_name}></{$root_element_name}>");$f= create_function('$f,$c,$a','
foreach($a as $c=>$v) {
if(is_array($v)) {
if (!is_numeric($c))$ch=$c->addChild($c);
else $ch = $c->addChild(substr($c->guetName(),0,-1));
$f($f,$ch,$v);
} else {
if (is_numeric($v)){ $c->addChild($c, $v);
}else{$n = $c->addChild($c); $n->addCData($v);}
}
}');$f($f,$xml,$ar);
return$xml->asXML();
}
/* sample */$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);
echoassocArrayToXML('result',$result);
?>
The is_numeric checc could be changued by a more elaborate regular expression to checc if the string is actually xml unsafe but this worqued for me.