循环读取PHP readfile或file_get_contents [英] PHP readfile or file_get_contents in a loop
问题描述
可能还有其他方法可以做到这一点,但我正在寻找一种相当简单的设置,因为它基本上是一次性过程.
there may be other ways to do this but I'm looking for an fairly easy set-up because it's basically a one-time process.
我有50个状态目录,每个目录中都有一些txt文件.
I have 50 state directories with a handful of txt files in each one.
我想进入每个目录,读取"每个文件(然后对每个文件进行mysql插入)
I want to step into each directory, "read" each file (and then do a mysql insert of each file)
我尝试了一些变体,但是每次尝试遍历并使用readfile或file_get_contents时,它都会在第一个文件之后中断,并且我无法打开流:列表其余部分上的错误.
I've tried a few variations, but each time I try to loop through and use readfile or file_get_contents it breaks after the first file and I get failed to open stream: errors on the remainder of the list.
我一直在寻找在循环中使用这些功能的陷阱,期望有许多原因导致他们不这样做,但没有得到答案.
I've searched for the pitfalls of using these functions in a loop expecting many reasons why not to, but not getting answers.
谢谢 回来添加示例代码-我看到列出了一个答案,所以我也将进行检查. (这都不是我的,我只是找到了一个捕获文件列表的函数)
thanks came back to add example code - I see there is an answer listed so I 'll check that out also. (none of this is mine, I simply found a function to capture the file list)
function listFilesInDir($start_dir)
{
/*
returns an array of files in $start_dir (not recursive)
*/
$files = array();
$dir = opendir($start_dir);
while(($myfile = readdir($dir)) !== false)
{
if($myfile != '.' && $myfile != '..')
{
$files[] = $myfile;
}
}
closedir($dir);
return $files;
}
$dir = 'path/to/files';
$Docs = listFilesInDir($dir);
foreach($Docs as $key => $fileName)
{
// HERE IS WHERE I TRIED THE file_get_contents
$content = file_get_contents($fileName);
//even doing an echo as a test would break it after the first file
echo $content;
//ultimately I would just do INSERT INTO here for mysql
}
推荐答案
以下是我要使用的一些变体. YMMV取决于您在做什么.如果您发布代码,我们可以解决您的特定实现,而不仅仅是提供替代解决方案:-)
Some variation of the below is what i would use. YMMV depending on what you're doing. If you post your code we can address your specific implementation instead of just providing alternate solutions :-)
$dir = new DirectoryIterator('/path/to/states');
foreach($dir as $file)
{
if(!$file->isDot() && $file->isFile() && strpos($file->getFilename(), '.txt') !== false)
{
$content = file_get_contents($file->getPathname());
if($content)
{
// do your insert code
}
}
}
这篇关于循环读取PHP readfile或file_get_contents的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!