使用 DOMDocument 解析 HTML 和 JS 代码
我将 HTML 作为字符串输入,然后解析它以将所有 href 链接更改为其他内容。然而,当 HTML 页面有一些 JS 脚本标签(即 )时,它会被删除!例如,这一行:
<script type="text/javascript" src="/js/jquery.js"></script>
更改为:
[removed][removed]
但是,我想保留所有内容。这是我的职能:
function parse_html_code($code, $code_id){
libxml_use_internal_errors(true);
$xml = new DOMDocument();
$xml->loadHTML($code);
foreach($xml->getElementsByTagName('a') as $link) {
$link->setAttribute('href', CLK_BASE."clk.php?i=$code_id&j=" . $link->getAttribute('href'));
}
return $xml->saveHTML();
}
我感谢对此的任何帮助。
I take HTML in as a string and then I parse it to change all href links to something else. This works however, when the HTML page has some JS script tags i.e. <script>
it gets removed! For example this line:
<script type="text/javascript" src="/js/jquery.js"></script>
Gets Changed to:
[removed][removed]
However, I would like to keep everything in. This is my function:
function parse_html_code($code, $code_id){
libxml_use_internal_errors(true);
$xml = new DOMDocument();
$xml->loadHTML($code);
foreach($xml->getElementsByTagName('a') as $link) {
$link->setAttribute('href', CLK_BASE."clk.php?i=$code_id&j=" . $link->getAttribute('href'));
}
return $xml->saveHTML();
}
I appreciate any help on this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
CodeIgniter 的虚假反 XSS“功能”会在 DOMDocument 查看脚本输入之前对其进行破坏。脚本标签和各种其他字符串将被删除,并替换为“[removed]”其他无缘由的混乱内容。有关完整的令人尴尬的详细信息,请参阅 system/libraries/Security.php 模块。
要关闭此误导性功能,请设置
$config['global_xss_filtering']= FALSE
。当然,您必须确保您的脚本实际上正确处理字符串转义(例如,在包含在页面中时始终对用户输入进行 HTML 转义)。但无论如何你都必须这样做;反 XSS 并不能解决您的文本处理问题,它只是掩盖它们。您需要对
getAttribute('href')
进行urlencode
(如果它不仅仅是数字或其他内容,还可能需要 $code_id)。CodeIgniter's bogus anti-XSS ‘feature’ is mauling your script's input before DOMDocument gets a look at it. Script tags and various other strings will be removed, replaced with “[removed]” other otherwise messed-about with for no good reason. See the system/libraries/Security.php module for the full embarrassing details.
To turn off this misguided feature, set
$config['global_xss_filtering']= FALSE
. You'll have to make sure your script is actually handling string escaping properly, of course (eg always HTML-escaping user input when including in a page). But then you have to do that anyway; anti-XSS doesn't fix your text processing problems, it just obscures them.You'll need to
urlencode
thatgetAttribute('href')
(and potentially $code_id if it's not just numeric or something).