我使用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();
只需在执行任何操作之前检查图像是否存在:
$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;
}