【发布时间】:2021-05-15 05:45:05
【问题描述】:
我需要在 PHP 中提取一个 tar.gz 文件。该文件包含许多 JSON 文件、tar.gz、zip 文件和子目录。我只需要将 JSON 文件移动到目录 ./Dataset/processing 并继续提取嵌套的 tar.gz 和 zip 以从那里获取所有 JSON 文件。这些文件也可能有嵌套的文件夹/目录。
结构如下:
origin.tar.gz
├───sub1.tar.gz
│ ├───sub2.tar.gz
│ ├───├───a.json
│ ├───├───├───├───├───├───...(unknown depth)
│ ├───b.json
│ ├───c.json
├───sub3.zip
│ ├───sub4.tar.gz
│ ├───├───d.json
│ ├───├───├───├───├───├───...(unknown depth)
│ ├───e.json
│ ├───f.json
├───subdirectory
│ ├───g.json
├───h.json
├───i.json
| ..........
| ..........
| ..........
| many of them
提取后./Dataset将如下所示
Dataset/processing
├───a.json
├───b.json
├───c.json
├───d.json
├───e.json
├───f.json
├───g.json
├───h.json
├───i.json
| ..........
| ..........
| ..........
| many of them
我知道如何在 PHP 中使用 PharData 提取 tar.gz,但它仅适用于单层深度。我在想,如果某种递归可以使这项工作适用于多级深度。
$phar = new PharData('origin.tar.gz');
$phar->extractTo('/full/path'); // extract all files in the tar.gz
我已经稍微改进了我的代码并尝试了这个,它适用于多深度但当有一个目录(文件夹或嵌套文件夹)也包含 JSON 时会失败。谁能帮我提取它们。
<?php
$path = './';
// Extraction of compressed file
function fun($path) {
$array = scandir($path);
for ($i = 0; $i < count($array); $i++) {
if($i == 0 OR $i == 1){continue;}
else {
$item = $array[$i];
$fileExt = explode('.', $item);
// Getting the extension of the file
$fileActualExt = strtolower(end($fileExt));
if(($fileActualExt == 'gz') or ($fileActualExt == 'zip')){
$pathnew = $path.$item; // Dataset ./data1.tar.gz
$phar = new PharData($pathnew);
// Moving the files
$phar->extractTo($path);
// Del the files
unlink($pathnew);
$i=0;
}
}
$array = scandir($path);
}
}
fun($path);
// Move only the json to ./dataset(I will add it later)
?>
提前致谢。
【问题讨论】:
-
欢迎来到 Stack Overflow。 SO is a question and answer page for professional and enthusiast programmers。请在您的问题中添加您自己的代码。您应该至少展示自己为解决这个问题所做的研究。
-
我是 Stack Overflow 的新手。非常感谢您的鼓励。我添加了我所做的研究量以及我为解决问题所做的努力以获得所需的解决方案。我仍然遇到我上面提到的问题。任何帮助将不胜感激。
标签: php json zip tar data-extraction