php - DOMDocument 删除脚本标签中的结束标签

标签 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();

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

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>

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

最佳答案

想到的唯一解决方案是预先匹配脚本标签,然后将它们替换为临时持有者,如 <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;

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

关于php - DOMDocument 删除脚本标签中的结束标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33426788/

相关文章:

php - mod_rewrite、php 和 .htaccess 文件

javascript - 如何在页面加载时使用 Featherlight 打开 DOM 元素?

php - 如何使用 php、DomDocument 和 DomXPath 查询 graphml?

php - 检查 domnodelist->item(x)->nodeValue == "nbsp;"

php - ™ 被转换为 ™ DOMDocument XPath

php - 在多语言网站中使用 PHP Gettext 扩展与 PHP 数组?

php - Zend_Date : How to get the date of an upcoming day?

javascript - 强制 DOM 替换触发显示动画

javascript - 为什么 `value` 属性为空而 `value` 属性具有正确的值?

javascript - Ajax 帖子未完成