如何使用PHP向元素添加属性?

时间:2018-04-11 08:50:14

标签: php html

这是我的代码:

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"添加到该元素?

2 个答案:

答案 0 :(得分:0)

您可以通过

执行此操作

$ node-&gt; setAttribute('rel','nofollow');

您也可以参考:

http://php.net/manual/en/class.domdocument.php

https://stackoverflow.com/a/6160661/6429700

答案 1 :(得分:0)

应该是

$myNode=  $node->nodeName;

$domAttribute = $myNode->createAttribute('rel');
$domAttribute->value = 'nofollow';

http://php.net/manual/en/domdocument.createattribute.php