gpt4 book ai didi

javascript - DOMDocument 去除 JavaScript 字符串中的 HTML 标签

转载 作者:行者123 更新时间:2023-11-30 05:34:48 24 4
gpt4 key购买 nike

我开发 PHP 应用程序已经有一段时间了。但是这个真的让我很挣扎。我正在使用 DomDocument 加载完整的 HTML 页面。这些页面是外部的,可能包含 JavaScript。这是我无法控制的。

在一些页面上,当归结为 JavaScript 字符串中的基本 HTML 格式时,事情并没有按照预期的方式呈现。我写下了一个例子来解释这一切。

<?php
$html = new DOMDocument();

libxml_use_internal_errors(true);

$strPage = '<html>
<head>
<title>Demo</title>
<script type="text/javascript">
var strJS = "<b>This is bold.</b><br /><br />This should not be bold. Where did my closing tag go to?";
</script>
</head>
<body>
<script type="text/javascript">
document.write(strJS);
</script>
</body>
</html>';

$html->loadHTML($strPage);
echo $html->saveHTML();
exit;
?>

我错过了什么吗?

编辑:我已经更改了演示。将 LoadHTML 更改为 LoadXML 现在不再起作用,演示的输出将通过 w3c 验证。将 CDATA block 添加到 JavaScript 似乎也没有任何效果。

最佳答案

LIBXML_SCHEMA_CREATE 添加到 loadHTML() 选项将解决此问题。

<?php
$html = new DOMDocument();

libxml_use_internal_errors(true);

$strPage = '<html>
<head>
<title>Demo</title>
<script type="text/javascript">
var strJS = "<b>This is bold.</b><br /><br />This should not be bold. Where did my closing tag go to?";
</script>
</head>
<body>
<script type="text/javascript">
document.write(strJS);
</script>
</body>
</html>';

$html->loadHTML($strPage, LIBXML_HTML_NODEFDTD | LIBXML_SCHEMA_CREATE);
echo $html->saveHTML();
exit();


?>

关于javascript - DOMDocument 去除 JavaScript 字符串中的 HTML 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24575136/

24 4 0