[英]Trying to echo contents of multiple text files while sorting the output by the file name - PHP
I'm not a developer, but I'm the default developer at work now. 我不是开发人员,但是我现在是工作中的默认开发人员。 : ) Over the last few weeks I've found a lot of my answers here and at other sites, but this latest problem has me confused beyond belief. :)在过去的几周里,我在这里和其他站点上找到了很多答案,但是这个最新的问题使我感到难以置信。 I KNOW it's a simple answer, but I'm not asking Google the right questions. 我知道这是一个简单的答案,但是我并不是在问Google正确的问题。
First... I have to use text files, as I don't have access to a database (things are locked down TIGHT where I work). 首先...我必须使用文本文件,因为我无权访问数据库(在我工作的地方事物被锁定在TIGHT内)。
Anyway, I need to look into a directory for text files stored there, open each file and display a small amount of text, while making sure the text I display is sorted by the file name. 无论如何,我需要查看目录中存储的文本文件,打开每个文件并显示少量文本,同时确保我显示的文本按文件名排序。
I'm CLOSE, I know it... I finally managed to figure out sorting, and I know how to read into a directory and display the contents of the files, but I'm having a heck of a time merging those two concepts together. 我关闭了,我知道了...我终于设法弄清楚了排序,而且我知道如何读入目录并显示文件的内容,但是我很难将这两个概念合并在一起一起。
Can anyone provide a bit of help? 谁能提供一些帮助? With the script as it is now, I echo the sorted file names with no problem. 使用现在的脚本,我可以毫无问题地回显排序的文件名。 My line of code that I thought would read the contents of a file and then display it is only echoing the line breaks, but not the contents of the files. 我以为我的代码行会读取文件的内容,然后显示它,只是回显换行符,而不回显文件的内容。 This is the code I've got so far - it's just test code so I can get the functionality working. 这是我到目前为止获得的代码-仅仅是测试代码,因此我可以使功能正常工作。
<?php
$dirFiles = array();
if ($handle = opendir('./event-titles')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$dirFiles[] = $file;
}
}
closedir($handle);
}
sort($dirFiles);
foreach($dirFiles as $file)
{
$fileContents = file_get_contents($file);//////// This is what's not working
echo $file."<br>".$fileContents."<br/><br/>";
}
?>
Help? 救命? : ) :)
Dave 戴夫
$files = scandir('./event-titles')
will return an array of filenames in filename-sorted order. $files = scandir('./event-titles')
将按文件名排序顺序返回文件名数组。 You can then do 然后你可以做
foreach($files as $file)
{
$fileContents = file_get_contents('./event-titles/'.$file);
echo $file."<br/>".$fileContents."<br/><br/>";
}
Note that I use the directory name in the file_get_contents call, as the filename by itself will cause file_get_contents to look in the current directory, not the directory you were specifying in scandir. 请注意,我在file_get_contents调用中使用目录名,因为文件名本身会导致file_get_contents查找当前目录,而不是您在scandir中指定的目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.