PHP RecursiveIteratorIterator图库

时间:2013-01-30 15:17:48

标签: php

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

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

我主要在那里,但是有一些额外的字符出现,阻止图像显示。

CODE (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的代码是添加额外的字符/创建浏览器无法正确读取的字符。

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

2 个答案:

答案 0 :(得分:1)

您忘了关闭图片代码:

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

答案 1 :(得分:0)

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

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