2015-04-23 47 views
6

我已经一个简单的函数,它有两个参数,一个是图像的URL,以及其他用于图像这段代码有什么问题? HTML + PHP

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> 

我不知道什么是错在这里输出,我使用的引导

+4

在你的函数中使用'return'而不是'echo'。 –

+0

你确定这是你得到的输出吗?输出与你的'echo'不一致。 –

回答

1

只需使用return语句,而不是回声在你的功能和你的问题应该被解决;-)

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语句应该解决您的问题

+0

使用@是不好的,你应该使用try catch块。它不好,只是当我们知道会有一个 – Vignesh

0

更好的方法是验证您的图像是否存在(删除@),然后retu rn(而不是echo):

... 

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.'/>' 

... 
+0

@时有什么用处? – runningmark

+0

你正在使用“@”(@getimagesize($ url)来隐藏任何应该显示的警告,所以我认为最好是检查文件是否真的存在,然后做任何你想做的事情...... –