1

我正在使用生成的 ID 打印图像。但是我想检查一下这个图像是否存在以及它是否不打印 no-image.jpg ......

<img src="phpThumb/phpThumb.php?src=../public/images/'.$row["id"].'/th.jpg&w=162" alt="" width="162" /> 

如果可以将其保留在一条线上,那就太好了。任何帮助,将不胜感激。

4

3 回答 3

3

我的建议实际上是从 html 标记本身抽象决策,在一个单独的不输出 html 的 php 逻辑块中......这是一个简短的示例,假设您没有使用模板引擎或 MVC 框架。

<?php
$filename = 'th.jpg';
$filePath = '/public/images/' . $row['id'] '/';
$webPath  = '/images/' . $row['id'] . '/'; 
//Logic to get the row id etc
if (!file_exists($filePath . $filename)) {
    $filename ='no-image.jpg';
    $webPath  = '/images/';
}
?>
<img src="<?php echo $webpath . $filename;?>" />
于 2009-12-30T22:30:13.423 回答
3

Kristopher Ives 所说的和file_exists

echo (file_exists("/path/file/name/here") ? "web/path/goes/here" : "no_image.jpg")

顺便说一句,您的代码段不太可能工作,因为您似乎将纯 HTML 输出和 PHP 组合在一起,而没有将 PHP 放入<? ?>

于 2009-12-30T21:15:18.250 回答
2

哇,这个问题被问了很多,并得到了很多回答:

http://en.wikipedia.org/wiki/Ternary_operation

你可以这样做:

<img src="<?php ($row['id'] != 0) ? "../public/{$row['id']}.jpeg" : 'no_image.jpg'; ?> >
于 2009-12-30T21:13:38.330 回答