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
/**
* Append Caracter Data to a node and check for a javascript node
*
* @param DOMElement $appendToNode
* @param string $text
*/
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>
DOMDocument::createCDATASection
(No version information available, might be only in CVS)
DOMDocument::createCDATASection — Crée un nouveau noeud cdata
Description
DOMCDATASection DOMDocument::createCDATASection
( string $data
)
Cette fonction crée une nouvelle instance de la classe DOMCDATASection. Ce noeud ne sera pas affiché dans le document, à moins qu'il ne soit inséré avec DOMNode->appendChild().
Liste de paramètres
- data
-
Le contenu du cdata.
Valeurs de retour
Le nouveau DOMCDATASection ou FALSE si une erreur survient.
Voir aussi
- DOMNode::appendChild
- DOMDocument::createAttribute
- DOMDocument::createAttributeNS
- DOMDocument::createComment
- DOMDocument::createDocumentFragment
- DOMDocument::createElement
- DOMDocument::createElementNS
- DOMDocument::createEntityReference
- DOMDocument::createProcessingInstruction
- DOMDocument::createTextNode
DOMDocument::createCDATASection
info at troptoek dot com
25-Mar-2008 06:40
25-Mar-2008 06:40
loathsome
04-Aug-2007 11:28
04-Aug-2007 11:28
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);
}
?>
