DOMDocument从内联脚本PHP中剥离标记

This is a strange one but looks like $dom->saveHTML() is stripping tags from inline javascript

$domStr = '
<!DOCTYPE html>
   <html>
    <head>
        <meta charset="utf-8"/>
        <title>my page</title>
        <script>
            var elem = "<div>some content</div>";
        </script>
    </head>
    <body>
        <div>
            MY PAGE
        </div>
    </body>
</html>
';
    $doc = new DOMDocument();
    libxml_use_internal_errors(true);//prevents tags in js from throwing errors; see php.net manual
    $doc->formatOutput = true;
    $doc->strictErrorChecking = false;
    $doc->preserveWhiteSpace  = true;

    $doc->loadHTML($domStr);
    echo $doc->saveHTML();
exit;

http://sandbox.onlinephpfunctions.com/code/ad59a2a1016b2128e437ef61dbe00f1c511bff8d

if you use libxml_use_internal_errors(true); you will not see what is wrong but if removed you get

<b>Warning</b>:  DOMDocument::loadHTML(): Unexpected end tag : div

Same thing happens with

$doc->formatOutput = false;

Any help is appreciated.

You're missing the opening <html> tag right after the DOCTYPE declaration.

I've avoided this by not including any HTML in my inline JavaScript. Instead, I've added <template> elements containing the HTML string I want to manipulate in JS, and then I read that dynamically at runtime. For example:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>my page</title>
    </head>

    <body>
        <div>
            MY PAGE
        </div>

        <template id="content-template">
            <div>some content</div>
        </template>

        <script>
            var elem = document.getElementById('content-template').innerHTML;
            ...
        </script>
    </body>
</html>