这是我的代码:
class xss_protector
{
public function sanitizeTags($html){
// to make tags stable, wrap them into <html> tag
$post_content_html = "<html>".$html."</html>";
$dom = new DOMDocument;
$dom->loadHTML(mb_convert_encoding($post_content_html, 'HTML-ENTITIES', 'UTF-8'), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//@*');
foreach ($nodes as $node) {
if($node->nodeName != "src" && $node->nodeName != "href" && $node->nodeName != "alt") {
$node->parentNode->removeAttribute($node->nodeName);
}
}
$post_content_html = $dom->saveHTML();
// To strip <html> tag which been wrapped
$post_content_html = preg_replace('/^<html>/', '', $post_content_html);
$post_content_html = preg_replace('/<\/html>$/', '', $post_content_html);
return $post_content_html;
}
}
如你所见,有这样的条件:
if($node->nodeName != "src" && $node->nodeName != "href" && $node->nodeName != "alt") {
现在我需要像这样添加elseif
块:
if($node->nodeName != "src" && $node->nodeName != "href" && $node->nodeName != "alt") {
.
.
} elseif ( $node->nodeName == "href" ) {
// Add rel="nofollow" attribute to the element
}
如何将rel="nofollow"
添加到该元素?
答案 0 :(得分:0)
您可以通过
执行此操作$ node-&gt; setAttribute('rel','nofollow');
您也可以参考:
答案 1 :(得分:0)
应该是
$myNode= $node->nodeName;
$domAttribute = $myNode->createAttribute('rel');
$domAttribute->value = 'nofollow';