簡體   English   中英

這段代碼有什么問題? html + php

[英]what is wrong with this piece of code? html + php

我有一個簡單的函數,它有兩個參數,一個用於圖像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>

我不知道這里有什么問題,我正在使用bootstrap

只需在函數中使用return語句而不是echo,你的問題就應該解決;-)

當需要從函數返回值時,請使用return語句而不是echo

當使用echo ,輸出立即被打印而不是返回到函數調用的位置。 這是一個例子。

function printer(){
    echo 'second';  
}

echo 'first'.' '.printer().' '.'last';

輸出:

secondfirst  last

這與您的代碼完全相同。 image_found()的回image_found()被打印為

<img src="http://localhost/nsc/product_images/7908076366784972032090.jpg" height="200px" width="100%"/>

echo語句的其余部分打印為

<a href="#"></a>

因此,使用return語句可以解決您的問題

更好的方法是驗證您的圖像是否存在(刪除@)然后返回(而不是回聲):

...

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

...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM