如何从目录显示图像并获得每个图像的相应描述,请说明存在。
目录中的
01.png
01.txt
02.png
03.png
03.txt
etc.
显示为//
<img src="01.png"><br>This is the description from the text file named 01.txt
<img src="02.png"><br>
<img src="03.png"><br>This is the description from the text file named 03.txt
我一直在搜索和搜索,但找不到任何东西,所以如果有人能指出我正确的方向,我将不胜感激。此外,对于想要创建非常简单的图库或图像和名称列表的人来说,这是非常有用的。
提前致谢!
答案 0 :(得分:3)
这是您正在寻找的内容,因为必须从相应的.txt
文件中动态捕获说明:
$dir = './';
$files = glob( $dir . '*.png');
foreach( $files as $file) {
$filename = pathinfo( $file, PATHINFO_FILENAME) . '.txt';
$description = file_exists( $filename) ? file_get_contents( $filename) : '';
echo '<img src="' . $file . '"><br>' . $description;
}
它的作用是从给定目录(*.png
)中使用glob()
抓取一组$dir
个文件。然后,对于每个图像,它获取图像的文件名(因此01.png
将为01
),并附加.txt
以获取描述文件的名称。然后,如果描述文件存在,则使用file_get_contents()
将描述文件加载到$description
变量中。然后它输出所需的HTML。
答案 1 :(得分:2)
我假设您将.php文件放在与图片和文本文件相同的目录中。
您可以使用函数glob()
从目录中读取所有图像文件作为数组,切断文件扩展名(因此'01 .png'变为'01')并附加字符串连接的文件扩展名。
工作代码示例可能如下所示:
<?php
$path_to_directory = './';
$pics = glob($path_to_directory . '*.png');
foreach($pics as $pic)
{
$pic = basename($pic, '.png'); // remove file extension
echo '<img src=\"{$pic}.png\"><br>';
if(file_exists($pic . '.txt'))
{
echo file_get_contents("{$pic}.txt");
}
}
?>
所以一定要看看这些功能:
快乐的编码。
答案 2 :(得分:1)
你的问题有点令人困惑。
制作包含所有信息的数组。
$pics = array('img' => '01.png', 'text' => 'This is the description');
foreach($pics as $pic) {
echo '<img src="'.$pic['name'].'" alt="">' . $pic['text'];
}
因此,您必须将您的信息放在数组或数据库中,否则您无法将描述映射到您的图像。
当你想要动态地阅读文件夹时,它有点困难。
您可以查看readdir或glob,然后您可以阅读所有图片获取名称并使用file_get_contents加载文本文件,但我认为它不是一种真正高效的方式。
答案 3 :(得分:0)
代码从此处修改:http://php.net/manual/en/function.readdir.php
//path to directory to scan
$directory = "../images/team/harry/";
//get all image files with a .jpg extension.
$images = glob($directory . "*.jpg");
//print each file name
foreach($images as $image)
{
print "<img src=\"$image\"><br>This is the description from the text file named $image";
}
好的,所以这不会打印文本文件的内容,但我相信你可以进一步修改上面的代码来搞清楚
YEP
答案 4 :(得分:0)
更新了ZnArKs代码的版本,因为他错过了你想要的文件内容
//path to directory to scan
$directory = "../images/team/harry/";
//get all image files with a .jpg extension.
$images = glob($directory . "*.png");
//print each file name
foreach($images as $image)
{
$textfile = substr($image, 0, -3) . "txt";
echo "<img src='{$image}'><br/>";
if(file_exists($textfile))
{
echo file_get_contents($textfile) . "<br/>";
}
}