DOMDocument 中加载的模板中的 PHP 代码块

发布于 2024-12-22 14:43:46 字数 213 浏览 5 评论 0原文

我需要使用 DOMDocument 解析 HTML 模板。但 HTML 代码可能包含 PHP 代码块,例如:

当我加载此 HTML 时,出现错误“Unescaped '<'属性值中不允许...”。解析器认为属性“data”没有结束引号,并且

I need to parse HTML-template with DOMDocument. But HTML code may contain PHP-code blocks, for example:

<div id="test" data="<?php echo $somevar?>"> </div>

When I load this HTML I get error "Unescaped '<' not allowed in attributes values...". Parser thinks that attribute "data" has no closing quote and <php is new tag. How can I specify to ignore <php tag or something like that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

平生欢 2024-12-29 14:43:46

您的 HTML 代码:

<div id="test" data="<?php echo $somevar?>"> </div>

不是 XML 代码。对于 XML 无效,HTML 则可以。要使用 DOMDocument 加载 HTML 代码,您可以使用 DOMDocument::loadHTML文档函数。

它将加载您的模板,不会出现任何错误。

示例/演示

$html = '<div id="test" data="<?php echo $somevar?>"> </div>';
$doc = new DOMDocument();
$doc->loadHTML($html);

相关:PHP 可以仅包含文件的指定部分吗?

Your HTML code:

<div id="test" data="<?php echo $somevar?>"> </div>

Is not XML code. For XML it's invalid, HTML is okay. To load HTML code with DOMDocument, you can use the DOMDocument::loadHTML­Docs function.

It will load your template without any error.

Example / Demo:

$html = '<div id="test" data="<?php echo $somevar?>"> </div>';
$doc = new DOMDocument();
$doc->loadHTML($html);

Related: Can PHP include work for only a specified portion of a file?

Oo萌小芽oO 2024-12-29 14:43:46

如果您尝试解析其中包含 PHP 标签的文档,您应该删除这些标签,或者首先捕获文件的输出,然后解析它。

您可以使用 ob_start()ob_get_clean(); 捕获文件的输出。

您可以使用正则表达式删除 PHP 标签:

$cleaned = preg_replace("/<\?php.*?\?>/i","",$input);

If you try to parse a document with PHP tags in it, you should remove those, or capture the output of the file first, and then parse it.

You can capture the output of the file with ob_start() and ob_get_clean();.

You can remove the PHP tags with regex:

$cleaned = preg_replace("/<\?php.*?\?>/i","",$input);
悲喜皆因你 2024-12-29 14:43:46

这感觉很黑客,但是...

$doc->loadHtml(str_replace('<?php', '<?php', file_get_contents($file)));

This feels hacky, but...

$doc->loadHtml(str_replace('<?php', '<?php', file_get_contents($file)));
悲凉≈ 2024-12-29 14:43:46

尝试:

<div id="test" data="<?= htmlentities($somevar) ?>"> </div>

您还可以尝试 htmlspecialchars(),它是 htmlentities() 的“更轻”版本。

Try:

<div id="test" data="<?= htmlentities($somevar) ?>"> </div>

You can also try htmlspecialchars(), which is a "lighter" version of htmlentities().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文