DOMDocument 中加载的模板中的 PHP 代码块
我需要使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的 HTML 代码:
不是 XML 代码。对于 XML 无效,HTML 则可以。要使用 DOMDocument 加载 HTML 代码,您可以使用
DOMDocument::loadHTML文档
函数。
它将加载您的模板,不会出现任何错误。
示例/演示:
相关:PHP 可以仅包含文件的指定部分吗?
Your HTML code:
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:
Related: Can PHP include work for only a specified portion of a file?
如果您尝试解析其中包含 PHP 标签的文档,您应该删除这些标签,或者首先捕获文件的输出,然后解析它。
您可以使用
ob_start()
和ob_get_clean();
捕获文件的输出。您可以使用正则表达式删除 PHP 标签:
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()
andob_get_clean();
.You can remove the PHP tags with regex:
这感觉很黑客,但是...
This feels hacky, but...
尝试:
您还可以尝试
htmlspecialchars()
,它是htmlentities()
的“更轻”版本。Try:
You can also try
htmlspecialchars()
, which is a "lighter" version ofhtmlentities()
.