2014-09-27 62 views
0

我正在使用DOMDocument来取代img src/height/width动态格式取决于包含div大小。它工作正常,除非它试图解析从服务器上删除的映像,这通常不会发生,但并非不可能,所以如果需要的话,我们需要处理它。DOMDocument挂在丢失的图像

任何想法我会怎么做?

谢谢!

$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(); 

回答

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; 
} 
+0

但是'src'不包含URL而不是文件路径?如果'src'只是有一些像“image.png”,并且在当前的工作目录中,这只会起作用。 – wavemode 2014-09-27 01:49:39

+0

url是一个文件路径。 – 2014-09-27 01:51:01

+0

我添加到脚本以防万一通过url访问它时遇到问题,您可以使用file_get_contents()代替。 – 2014-09-27 01:53:16