2014-09-27 80 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