johnmoe johnmoe - 8 days ago 6
CSS Question

Echo text with images inside php for loop

So I have a PHP script which gets all of the images in folder and I would like to add the filenames in a tag under them.

Tried GetElementById but I couldn't get it to work.

Thanks in advance.

Edit:Works now

PHP here:

<?php
$files = glob("img/*.*");
for ($i=0; $i<count($files); $i++) {
$image = $files[$i];
$filename = pathinfo($image);
echo '
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" src="'.$image .'"/>
</a>

<p>' . $filename['filename'] .'</p>

</div> ' ; }
?>

Answer

$image already stores a path to your file.

For example $image can be /upload/images/picture.jpg. Then to get filename (which is picture.jpg) you can use basename function:

echo '
    <div class="col-lg-3 col-md-4 col-xs-6 thumb">
        <a class="thumbnail" href="#">
            <img class="img-responsive" src="'.$image .'"/>
        </a>
        <p>' . basename($image) . '</p>
  </div>';

If you need to echo full file path - omit basename:

<p>' . $image . '</p>

And as already mentioned - using same id for several elements is a bad idea. Ids must be unique on a page. If you don't really need ids - just remove them as I did in my answer.

Comments