简体   繁体   中英

PHP for-loop with HTML inside not functioning properly

So, I'm trying to build a slideshow for a site I'm making, but it's unclear how many images I am going to have to include. The current code for retrieving the images is included below, but when run it is only displaying:

代码输出

<?php
                $dir = dirname(__FILE__).'/img';
                $images = scandir($dir);
                if($images)
                {
                    foreach($images as $image)
                    {?>
                        <div class="slide active-slide slide-feature">
                            <div class="container">
                                <div class="row">
                                    <div class="col-xs-12">
                                        <a href="#"><img src= <?php echo ('"' . $dir . '/' . $image . '"') ?> ></a>
                                    </div>
                                </div>
                            </div>
                        </div>
            <?php
                    }
                }
            ?>

Note: When I just type out the HTML by hand and include specific URLs, the HTML itself works fine, so I'm assuming it's an issue with the integration of HTML and PHP.

$dir = dirname(__FILE__).'/img';

In this context, $dir is an absolute filesystem path, not a URL. So, when you use $dir in the src attribute of the img element, the image is never going to be found. You could probably fix this by simply making the URL relative (although a root-relative URL would be preferable), for example:

<a href="#"><img src="img/<?=$image?>"></a>

You should also note that the scandir() function will also return the two "special" directories . and .. , so these will need to be skipped at the start of your foreach() loop. For example:

if (in_array($image,array('.','..'))) continue;

Mixing output inside PHP constructs in this way (by breaking in/out of PHP mode) is not good practice as it restricts portability, harder to read, harder to debug etc. Instead, consider assigning your output to a variable and echo'ing this at the end of your script.

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