[英]Open and read files in directory inside folder in PHP
Okay guys so I am a bit lost as to how to adjust my code. 好的,大家好,我对如何调整代码有些迷惑。 Up to now, I have my code to read any Json file in a directory, parse it and put it in a table - works great since I was only using 1 JSON file per table row. 到目前为止,我的代码可以读取目录中的任何Json文件,将其解析并放入表中-效果很好,因为我每表行仅使用1个JSON文件。
What I need to do now is the following, each IP address I have gives me 3 JSON files now that are placed into a folder with the IP address as its name. 我现在需要做的是,每个IP地址现在给我3个JSON文件,这些文件放在以IP地址作为名称的文件夹中。 In my main directory I will have many folder each with 3 JSON files in it. 在我的主目录中,我将有很多文件夹,每个文件夹中都有3个JSON文件。
I want to read each file in every folder, place the info I parse in a table and then move on to the next folder as a new row and do the same. 我想读取每个文件夹中的每个文件,将我解析的信息放在表中,然后作为新行移至下一个文件夹并执行相同的操作。
FOR REFERENCE::
Current file layout:
FOLDER-->JSON
-->JSON
-->JSON
New file layout:
FOLDER-->IPADDRESS-->JSONFILE1
-->JSONFILE2
-->JSONFILE3
-->IPADDRESS2-->JSONFILE1
--JSONFILE2
-->JSONFILE3
Current code for reading any JSON file in a directory: 用于读取目录中任何JSON文件的当前代码:
$dir = "my dir";
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
foreach(glob("*_name.json") as $filename) {
$data = file_get_contents($filename);
$testing = json_decode($data, true);
echo "<tr>";
echo "<td>{$filename }</td>";
foreach($testing[0] as $row) {
// code for parsing here ...
}
}
}
}
here you go using RecursiveIteratorIterator Class 在这里,您使用RecursiveIteratorIterator类
function Get_Files()
{
$dir = "my_dir";
$init = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
$files = array();
foreach ($init as $file) {
if ($file->isDir()) {
continue;
}
$files[] = $file->getPathname();
}
return $files;
}
foreach (Get_Files() as $file) {
$data = file_get_contents($file);
$testing = json_decode($data, true);
echo "<tr>";
echo "<td>{$file}</td></tr>";
}
output: 输出:
my_dir\192.168.0.1\JSONFILE1.json
my_dir\192.168.0.1\JSONFILE2.json
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.