繁体   English   中英

PHP DOMDocument 将引号作为特殊/HTML 字符返回

[英]PHP DOMDocument returning quotation marks as special/HTML characters

$string = '<p><a href="http://example.com">Link</a></p>'; // via $_POST['post-content']
$dom = new DOMDocument();
$dom->loadHTML($string);
$allowed_attributes = array('id','href', 'src', 'class', 'style', 'colspan', 'rowspan');
foreach($dom->getElementsByTagName('*') as $node){
    for($i = $node->attributes->length -1; $i >= 0; $i--){
        $attribute = $node->attributes->item($i);
        if(!in_array($attribute->name,$allowed_attributes)) $node->removeAttributeNode($attribute);
    }
}

$html = $dom->saveHTML();

结果...

<p><a href="%5C%22http://example.com%5C%22">Link</a></p>

...

我试过 html_entity_decode($html),但它不起作用。 我不明白是什么导致了这个问题。 我可以使用一些帮助。

我在处理 wordpress 过滤器时遇到了这个问题。 我发现在我的情况下,内容是通过 addslashes 运行的,而斜线导致了该返回。 上面的问题看起来像这样。

$string = stripslashes('<p><a href="http://example.com">Link</a></p>'); // via $_POST['post-content']
$dom = new DOMDocument();
$dom->loadHTML($string);
$allowed_attributes = array('id','href', 'src', 'class', 'style', 'colspan', 'rowspan');
foreach($dom->getElementsByTagName('*') as $node){
    for($i = $node->attributes->length -1; $i >= 0; $i--){
       $attribute = $node->attributes->item($i);
        if(!in_array($attribute->name,$allowed_attributes)) $node->removeAttributeNode($attribute);
    }
}

// Dont forget to add the slashes back in
$html = addslashes($dom->saveHTML());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM