DOMDocument 删除脚本标签内的结束标签

Get*_*awn 3 php dom domdocument

我有以下test.php文件,当我运行它时,结束</h1>标记被删除。

<?php

$doc = new DOMDocument();

$doc->loadHTML('<html>
    <head>
        <script>
            console.log("<h1>hello</h1>");
        </script>
    </head>
    <body>

    </body>
</html>');

echo $doc->saveHTML();
Run Code Online (Sandbox Code Playgroud)

这是我执行该文件时的结果:

PHP Warning:  DOMDocument::loadHTML(): Unexpected end tag : h1 in Entity, line: 4 in /home/ryan/NetBeansProjects/blog/test.php on line 14

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
    <head>
        <script>
            console.log("<h1>hello");
        </script>
    </head>
    <body>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

那么,为什么要删除标签呢?它是一个字符串,所以不应该忽略它吗?

小智 5

想到的唯一解决方案是 preg 匹配脚本标签,然后用临时持有者替换它们,例如<script id="myuniqueid"></script>在 dom 管理结束时再次替换为实际脚本,如下所示:

//  The dom doc
$doc = new DOMDocument();

//  The html
$html = '<html>
    <head>
        <script>
            console.log("<h1>hello</h1>");
        </script>
    </head>
    <body>

    </body>
</html>';

//  Patter for scripts
$pattern = "/<script([^']*?)<\/script>/";
//  Get all scripts
preg_match_all($pattern, $html, $matches);

//  Only unique scripts
$matches = array_unique( $matches[0] );

//  Construct the arrays for replacement
foreach ( $matches as $match ) {
  //  The simple script
  $id = uniqid('script_');
  $uniqueScript = "<script id=\"$id\"></script>";
  $simple[] = $uniqueScript;
  //  The complete script
  $complete[] = $match;
}

//  Replace the scripts with the simple scripts
$html = str_replace($complete, $simple, $html);
//  load the html into the dom
$doc->loadHTML( $html);

//  Do the dom management here
//  TODO: Whatever you do with the dom

//  When finished
//  Get the html back
$html = $doc->saveHTML();
//  Replace the scripts back
$html = str_replace($simple, $complete, $html);
//Print the result
echo $html;
Run Code Online (Sandbox Code Playgroud)

该解决方案打印干净,没有 dom 错误。


Gij*_*ese 5

传递LIBXML_SCHEMA_CREATE给 loadHTML 选项。这将解决这个问题。

<?php

$doc = new DOMDocument();

libxml_use_internal_errors(true);

$doc->loadHTML(
  '<html>
    <head>
        <script>
            console.log("<h1>hello</h1>");
        </script>
    </head>
    <body>

    </body>
</html>',
  LIBXML_HTML_NODEFDTD | LIBXML_SCHEMA_CREATE
);

echo $doc->saveHTML();
Run Code Online (Sandbox Code Playgroud)