What best practices should be followed when including PHP content in an HTML page using document.write?

When including PHP content in an HTML page using document.write, it is important to properly escape any special characters in the PHP content to prevent syntax errors or injection attacks. One way to achieve this is by using the htmlspecialchars() function in PHP to encode the content before outputting it with document.write.

<?php
$phpContent = "<p>This is PHP content</p>";
$escapedContent = htmlspecialchars($phpContent, ENT_QUOTES);
echo "<script>document.write('" . $escapedContent . "');</script>";
?>