【问题标题】:The setAttribute is ignored, why?setAttribute 被忽略,为什么?
【发布时间】:2018-01-30 17:34:10
【问题描述】:

此代码的目的是将 HTML 属性“data-original-src”添加到 img-tag 中,以防不安全的 http:// URL。但是没有生成这个属性。

出了什么问题,我忽略了什么错误? 无论如何,str_replace() 就像一个魅力。

public function parse($string) {
    if($this->settings['camo_enabled'] == true) {
        $doc = new DOMDocument();
        $doc->loadHTML($string);
        $images = $doc->getElementsByTagName('img');
        //$imgarray = array();
        foreach ($images as $image) {
            $url = $image->getAttribute('src');
            if(substr($url, 0, 8) != 'https://') {
                $image->setAttribute('data-original-src', $url);
                $camo = $this->proxy_url($url);
                $string = str_replace($image->getAttribute('src'), $camo, $string);
                unset($url, $camo);
            }
        }
    }
    return $string;
}

【问题讨论】:

    标签: php domdocument setattribute


    【解决方案1】:

    我认为问题出在您忘记修改您传递给调用saveHTML() 的方法的$string 变量,然后再返回它。按如下方式提交您的更改:

    public function parse($string)
    {
        if ($this->settings['camo_enabled'] == true)
        {
            $doc = new DOMDocument();
            $doc->loadHTML($string);
            $images = $doc->getElementsByTagName('img');
    
            foreach ($images as $image)
            {
                $url = $image->getAttribute('src');
    
                if (substr($url, 0, 8) != 'https://')
                {
                    $image->setAttribute('data-original-src', $url);
                    $camo = $this->proxy_url($url);
                    $string = str_replace($image->getAttribute('src'), $camo, $string);
                    unset($url, $camo);
                }
            }
        }
    
        $string = $doc->saveHTML(); 
        return $string;
    
        // The two lines above can also be simply rewritten as:
        // return $doc->saveHTML();
    }
    

    有关详细信息,请参阅official documentation

    附带说明,由于您正在对 $string 变量和已解析的 HTML 文件执行更改,请通过修改此行来坚持后者:

    $string = str_replace($image->getAttribute('src'), $camo, $string);
    

    进入:

    $image->setAttribute('src', $camo);
    

    【讨论】:

    • 这不是一个完整的解决方案。 HTML 现在给出了 data-original-src-attribute。这似乎是正确的,但 saveXML 提供了一个 doctype 和 HTML 文档,其中包含 body-tag。这打破了我的 HTML 文档的有效性任何想法?
    • 抱歉:php.net/manual/en/domdocument.savehtml.php,我将 XML 与 HTML 混淆了。我的答案现在已编辑。
    • 不,现在在我的 HTML 文档正文中看到一个 HTML 文档类型,它破坏了我的 HTML 文档的有效性。请注意,我将替换 HTML 文档的一部分,而不是整个文档!
    猜你喜欢
    • 2021-11-06
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多