PHP 递归迭代器迭代器图像库


PHP RecursiveIteratorIterator image gallery

使用SO其他地方的答案,我正在研究一个基本的PHP迭代器,以在嵌套DIR中显示图像。

我的目标是让 PHP 运行 DIR 并添加一个 IMG 标签,其中 SRC 指向它迭代的文件。

我大部分时间都在那里,但是出现了一些额外的字符,这些字符会阻止图像显示。

代码(h2 和 h3 用于调试时的可读性,无论它们是否存在都存在问题):

// Create recursive dir iterator which skips dot folders
$dir = new RecursiveDirectoryIterator('./images/families/',
    FilesystemIterator::SKIP_DOTS);
// Flatten the recursive iterator, folders come before their files
$it  = new RecursiveIteratorIterator($dir,
    RecursiveIteratorIterator::CHILD_FIRST);
// Maximum depth is 1 level deeper than the base folder
$it->setMaxDepth(5);
// Basic loop displaying different messages based on file or folder
foreach ($it as $fileinfo) {
    if ($fileinfo->isDir()) {
        printf("<h2>Folder - %s'n</h2>", $fileinfo->getFilename());
    } elseif ($fileinfo->isFile()) {
        printf("<h3><img src='"images/families/%s/%s></h3>", $it->getSubPath(), $fileinfo->getFilename());
    }
}

通过浏览器中的视图源代码的结果:

Folder - smith/40th
<img src="images/families/smith/40th/40th_1.jpg>
<img src="images/families/smith/40th/40th_11.jpg>

..等


浏览器窗口中的结果(选择"在新窗口中打开图像"):

"The requested URL /images/families/smith/40th/40th_1.jpg><img src= was not found on this server.""
This is the URL in the address bar:
/images/families/smith/40th/40th_1.jpg%3E%3Cimg%20src=

所以我创建 img 的代码正在添加额外的字符/创建浏览器无法正确读取的字符。

这是编码问题吗?感谢您的阅读。

您忘记关闭图像标记:

printf("<h2>Folder - %s'n</h2>", $fileinfo->getFilename());
} elseif ($fileinfo->isFile()) {
    printf("<h3><img src='"images/families/%s/%s'"></h3>", $it->getSubPath(), $fileinfo->getFilename());
}

您刚刚错过了 src 属性中的结束引号,这导致它运行到后续标记上。

printf("<h3><img src='"images/families/%s/%s'"></h3>", $it->getSubPath(), $fileinfo->getFilename());
//-----------------------------------------^^^^^