Search code examples
phpjavascripthtmldomdocumentcdata

Problems with PHP DOMDocument LoadHTML when parsing CDATA Sections in Script tags


I have been getting this error when trying to parse HTML with a script tag using PHP's DOMDocument class.

Warning: DOMDocument::loadHTML(): Unexpected end tag : style in Entity, line: 71 in /var/www/signage-dev/dynaml/includes/page.php on line 95

I have even tried CDATA tags but it has resulted in the same error

My script tag is

<script type="text/javascript">
//<![CDATA[
document.write('<style type="text/css"> .printBTN { display: inline; } </style>');
//]]>   
</script>

This snippet is supposed to show a print button when JavaScript is enabled. I don't believe this is the most effective way of doing this (the previous developers created this), but even so, I wish to find a solution to this problem since I may run into this problem again in the future and it may not be as easy to fix as this is.


Solution

  • This question seems to have the solution Why split the tag when writing it with document.write()?

    I guess php DOM is more strict than most browsers. The solution I have seen sometimes is the one posted in a comment below the linked answer, escaping it with <\/script>, or in this case <\/style>, but I thought it was only necessary with script tags.