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
(PHP 5)
DOMDocument::createCDATASection — 新しい cdata ノードを作成する
説明
DOMCDATASection DOMDocument::createCDATASection
( string $data
)
この関数は、DOMCDATASection クラスの新しいインスタンスを作成します。このノードは、(たとえば) DOMNode->appendChild() などで 挿入されない限り、ドキュメント内に現われません。
パラメータ
- data
-
cdata の内容。
返り値
新しい DOMCDATASection、あるいはエラーが発生した場合は FALSE を返します。
参考
- DOMNode::appendChild - 子要素群の最後に新しい子要素を追加する
- DOMDocument::createAttribute - 新しい属性を作成する
- DOMDocument::createAttributeNS - 関連付けられた名前空間に新しい属性を作成する
- DOMDocument::createComment - 新しい comment ノードを作成する
- DOMDocument::createDocumentFragment - 新しい文書片を作成する
- DOMDocument::createElement - 新しい要素ノードを作成する
- DOMDocument::createElementNS - 関連付けられた名前空間に新しい要素を作成する
- DOMDocument::createEntityReference - 新しいエンティティ参照ノードを作成する
- DOMDocument::createProcessingInstruction - 新しい PI ノードを作成する
- DOMDocument::createTextNode - 新しいテキストノードを作成する
DOMDocument::createCDATASection
info at troptoek dot com
25-Mar-2008 02:40
25-Mar-2008 02:40
loathsome
05-Aug-2007 06:28
05-Aug-2007 06: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);
}
?>
