Close

DOMDocumentで HTMLの断片を挿入

JavaScript等で「element.innerHTML='<p>hoge</p>’;」てな感じに書くのと同等のことをしたいと。

9181.php
function addHtmlFragment($doc,$parent,$html)
{
$tempDoc=new DOMDocument('1.0','utf-8');
$tempDoc->loadHTML("<?xml encoding='utf-8' ?><html>$html</html>",LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD);
foreach($tempDoc->documentElement->childNodes as $child){
$parent->appendChild($doc->importNode($child,true));
}
}
$doc=new DOMDocument('1.0','utf-8');
$parent=$doc->createElement('div');
addHtmlFragment($doc,$parent,"<p>hoge</p>");

Leave a Reply

Your email address will not be published. Required fields are marked *

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)