【问题标题】:what is wrong with this piece of code? html + php这段代码有什么问题? html + php
【发布时间】:2015-07-01 15:48:57
【问题描述】:

我有一个简单的函数,它有两个参数,一个是图片的url,另一个是图片的属性

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>

我不知道这里出了什么问题,我正在使用引导程序

【问题讨论】:

  • 在你的函数中使用return而不是echo
  • 你确定这是你得到的输出吗?输出与您的echos 不一致。

标签: php html twitter-bootstrap


【解决方案1】:

只需在你的函数中使用 return 语句而不是 echo,你的问题应该会得到解决 ;-)

【讨论】:

    【解决方案2】:

    更好的方法是验证你的图片是否存在(去掉@)然后返回(而不是回显):

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

    【讨论】:

    • @有什么用?
    • 您正在使用 "@" (@getimagesize($url) 隐藏任何应该显示的警告,所以我认为最好检查文件是否真的存在,然后做任何你想做的事情。 ..
    【解决方案3】:

    当你需要从一个函数中返回一个值时,使用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 语句应该可以解决您的问题

    【讨论】:

    • 使用 @ 不好,你应该使用 try catch 块。当我们知道会有一个错误时,简单地隐藏一个错误是不好的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    • 2018-09-09
    相关资源
    最近更新 更多