DOMDocument挂起丢失的图像

时间:2014-09-27 01:15:41

标签: php image html-parsing domdocument

我使用DOMDocument将img src / height / width替换为动态格式,具体取决于包含的div大小。它工作正常,除非它试图解析已经从服务器删除的图像,这通常不会发生,但是不可能,所以我们需要处理它。如果是这样的话。

我会怎么做?

谢谢!

    $dom=new DOMDocument();
    $dom->loadHTML($footer, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    $imgs = $dom->getElementsByTagName("img");
    foreach($imgs as $img) {            

        // Resize 
        $src = $img->getAttribute('src');
        $params = array( 'width' => $width );
        $new_src = bfi_thumb( $src, $params );
        $img->setAttribute( 'src' , $new_src );

        // Set new dimensions
        $size = getimagesize($new_src);
        $img->removeAttribute('height');
        $img->removeAttribute('width');
        $img->setAttribute('height', $size[1]);
        $img->setAttribute('width', $size[0]);
    }   
    $footer = $dom->saveHTML();

1 个答案:

答案 0 :(得分:0)

在执行任何操作之前,只需检查图像是否存在:

$src = $img->getAttribute('src');
$exists = file_get_contents($src, NULL, NULL, NULL, 1);
if($exists) {
    $params = array( 'width' => $width );
    $new_src = bfi_thumb( $src, $params );
    $img->setAttribute( 'src' , $new_src );

    // Set new dimensions
    $size = getimagesize($new_src);
    $img->removeAttribute('height');
    $img->removeAttribute('width');
    $img->setAttribute('height', $size[1]);
    $img->setAttribute('width', $size[0]);
}

如果需要经常使用它,那么它可能会更好。

function srcExists($src) {
    $exists = file_get_contents($src, NULL, NULL, NULL, 1);
    return ($exists) ? true : false;
}