【发布时间】:2010-12-11 23:29:57
【问题描述】:
有没有办法从目录中提取图像并将它们放置在网页上,并在这些图像上附加链接,从而将人们带到使用 PHP 与该图像关联的特定网页?
谢谢
【问题讨论】:
有没有办法从目录中提取图像并将它们放置在网页上,并在这些图像上附加链接,从而将人们带到使用 PHP 与该图像关联的特定网页?
谢谢
【问题讨论】:
<?php
$directory = "imageDirectory"; // assuming that imageDirectory is in the same folder as the script/page executing the script
$contents = scandir($directory);
if ($contents) {
foreach($contents as $key => $value) {
if ($value == "." || $value == "..") {
unset($key);
}
}
}
echo "<ul>";
foreach($contents as $k => $v) {
echo "<li><a href=\"$directory/" . $v . "\">link text</a></li>";
}
echo "</ul>";
?>
这应该可以工作,尽管foreach() 在计算上可能很昂贵。而且我确信必须有更好/更经济的方法来删除第一个 foreach() 中 . 和 .. 的相对文件路径
【讨论】:
应该这样做:
if ($handle = opendir('/path/to/files')) {
echo "Directory handle: $handle\n";
echo "Files:\n";
/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) {
if(substr($file, -3) == 'jpg'){ //modify to handle filetypes you want
echo "<a href='/path/to/files/".$file."'>".$file."</a>";
}
}
closedir($handle);
}
【讨论】:
您是在问如何扫描目录或如何将图像列表与 url 关联?
第一个问题的答案是glob()函数
第二个答案是使用关联数组
$list = array('foo.gif' => 'bar.php', 'blah.gif' => 'quux.php');
还有一个用于输出图像和链接的 foreach 循环
foreach($list as $src => $href) echo "<a href='$href'><img src='$src'></a>";
【讨论】:
@ricebowl:
使用 PHP 版本 5.2.9/apache 2.0/windows vista - 我收到 Parse 错误。
无论如何,有可行的解决方案:
$dir = "./imageDirectory";
$ext = array('.jpg','.png','.gif');
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
print '<ul>';
if(strpos($filename, '.') > 3)
{
print '<li><a href="'.$dir.'/'.$filename.'">'.str_replace($ext, '', $filename).'</a></li>';
}
print '</ul>';
}
【讨论】: