我有一个简单的函数,它有两个参数,一个用于图像网址,另一个用于图像属性
function image_found($url,$attributes)
{
if(@getimagesize($url))
{
echo '<img src="'.$url.'" '.$attributes.'/>';
}
else
{
echo '<img src="'.base_url().'/site_images/image_not_found.svg" '.$attributes.'/>';
}
}
现在我要做的是创建一个可点击的图像,如果找到图像,现在这是html代码
echo '<div class="panel-body">';
echo '<div class="col-md-12 col-lg-12 col-sm-12 text-center">';
$url = base_url().'product_images/'.$result->product_image.'.'.$result->image_type;
$attributes = 'height="200px" width="100%"';
echo '<a href="product.com/full/url">'.image_found($url,$attributes).'</a>';
echo '</div>';
echo '</div>';
这是我得到的输出
<div class="panel-body">
<div class="col-md-12 col-lg-12 col-sm-12 text-center">
<img src="http://localhost/nsc/product_images/7908076366784972032090.jpg" height="200px" width="100%"/>
<a href="#"></a>
</div>
</div>
我不知道这里有什么问题,我正在使用bootstrap
答案 0 :(得分:1)
只需在函数中使用return语句而不是echo,就可以解决问题; - )
答案 1 :(得分:0)
当您需要从函数返回值时,请使用return
语句而不是echo
当使用echo
时,输出立即被打印而不是返回到函数调用的位置。这是一个例子。
function printer(){
echo 'second';
}
echo 'first'.' '.printer().' '.'last';
输出:
secondfirst last
这与您的代码完全相同。 image_found()
中的回显打印为
<img src="http://localhost/nsc/product_images/7908076366784972032090.jpg" height="200px" width="100%"/>
其余的echo语句打印为
<a href="#"></a>
因此,使用return语句可以解决您的问题
答案 2 :(得分:0)
更好的方法是验证您的图像是否存在(删除@)然后返回(而不是回声):
...
if(file_exists('your/path/to/image'))
return '<img src="'.$url.'" '.$attributes.'/>';
else
return '<img src="'.base_url().'/site_images/image_not_found.svg" '.$attributes.'/>'
...