setAttribute会被忽略,为什么?

时间:2018-01-29 23:15:23

标签: php domdocument setattribute

这段代码的意图是在http:// URL不安全的情况下,将HTML属性'data-original-src'添加到img-tag中。但是没有生成此属性。

出了什么问题,我忽略了什么错误? 无论如何,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;
}

1 个答案:

答案 0 :(得分:1)

我认为问题产生的原因是您在返回之前忘记修改传递给调用library(sf) library(sp) ## using a MULTIPOLYGON data set supplied with library(sf) nc <- sf::st_read(system.file("shape/nc.shp", package="sf")) ## convert the geometry of the `sf` object to SpatialPolygons spd <- sf::as_Spatial(st_geometry(nc), IDs = as.character(1:nrow(nc))) class(spd) # [1] "SpatialPolygons" # attr(,"package") # [1] "sp" ## grab the data from the sf object df <- nc df$geometry <- NULL df <- as.data.frame(df) ## create the SpatialPolygonsDataFrame spd <- sp::SpatialPolygonsDataFrame(spd, data = df) class(spd) # [1] "SpatialPolygonsDataFrame" # attr(,"package") # [1] "sp" head(spd@data) # AREA PERIMETER CNTY_ CNTY_ID NAME FIPS FIPSNO CRESS_ID BIR74 SID74 NWBIR74 BIR79 SID79 NWBIR79 # 1 0.114 1.442 1825 1825 Ashe 37009 37009 5 1091 1 10 1364 0 19 # 2 0.061 1.231 1827 1827 Alleghany 37005 37005 3 487 0 10 542 3 12 # 3 0.143 1.630 1828 1828 Surry 37171 37171 86 3188 5 208 3616 6 260 # 4 0.070 2.968 1831 1831 Currituck 37053 37053 27 508 1 123 830 2 145 # 5 0.153 2.206 1832 1832 Northampton 37131 37131 66 1421 9 1066 1606 3 1197 # 6 0.097 1.670 1833 1833 Hertford 37091 37091 46 1452 7 954 1838 5 1237 的方法的$string变量。按如下方式提交您的更改:

saveHTML()

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

另一方面,由于您在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(); } 变量和解析后的HTML文件中都进行了更改,因此请修改此行,坚持后者:

$string

成:

$string = str_replace($image->getAttribute('src'), $camo, $string);
相关问题