简体   繁体   中英

Use php function in img “src” tag

I want instead of specify the file name manually, to load the files dynamicly with function which return string with the file name.I have function in php, which show this code -

       <a >
        <figure>                                                        
        <img src=\"images/parfumes/car.png\" class=\"parfume$ProductID\"  value=\"$ProductPrice \" height=\"225\" width=\"225\">
        <figcaption  >Цена: $ProductPrice лв.</figcaption>
        </figure>

    </a>";

And this is the function which return the string:

function getPpicture($id)
{
    $path = 'images';
    $files = scandir($path);
    foreach ($files as $file) {
        if (is_file($file)) {
            echo "Файлът несъществува. Моля опитатайте отново!!";
        } else {
            $ext = basename($file, '.*');
            if ($ext == $id) {
               return  $ext . "";
               break;
            }

        }
    }
}

And i want something like that:

<img src=\"images/parfumes/getPpicture(somedigit)\"  class=\"parfume2\" value=\"$ProductPrice\" height=\"225\" width=\"225\">
        <figcaption  >$ProductPrice.ЛВ</figcaption>
        </figure>";

Any ideas, which is correct syntax??

This can be accomplished in 2 steps :

  1. assign id to your img tag (not necessary but more convenient)

  <img src="images/parfumes/getPpicture(somedigit)" id="myImg"class="parfume2" value="$ProductPrice" height="225" width="225"> 

  1. change src attribute of your image tag using javascript

  document.getElementById('myImg').src = "images/parfumes/" + getPpicture(somedigit); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM