我正在使用生成的 ID 打印图像。但是我想检查一下这个图像是否存在以及它是否不打印 no-image.jpg ......
<img src="phpThumb/phpThumb.php?src=../public/images/'.$row["id"].'/th.jpg&w=162" alt="" width="162" />
如果可以将其保留在一条线上,那就太好了。任何帮助,将不胜感激。
我正在使用生成的 ID 打印图像。但是我想检查一下这个图像是否存在以及它是否不打印 no-image.jpg ......
<img src="phpThumb/phpThumb.php?src=../public/images/'.$row["id"].'/th.jpg&w=162" alt="" width="162" />
如果可以将其保留在一条线上,那就太好了。任何帮助,将不胜感激。
我的建议实际上是从 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;?>" />
Kristopher Ives 所说的和file_exists:
echo (file_exists("/path/file/name/here") ? "web/path/goes/here" : "no_image.jpg")
顺便说一句,您的代码段不太可能工作,因为您似乎将纯 HTML 输出和 PHP 组合在一起,而没有将 PHP 放入<? ?>
哇,这个问题被问了很多,并得到了很多回答:
http://en.wikipedia.org/wiki/Ternary_operation
你可以这样做:
<img src="<?php ($row['id'] != 0) ? "../public/{$row['id']}.jpeg" : 'no_image.jpg'; ?> >