I need to extract a tar.gz file in PHP. The file contains many JSON files, tar.gz, zip files, and subdirectories. I need to move only the JSON files to a directory ./Dataset/processing and keep extracting the nested tar.gz and zip to get all the JSON files from there. Those files could also have nested folders/ directories.
The structure is like the following:
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
Once it gets extracted ./Dataset will look like this
Dataset/processing
├───a.json
├───b.json
├───c.json
├───d.json
├───e.json
├───f.json
├───g.json
├───h.json
├───i.json
| ..........
| ..........
| ..........
| many of them
I know how to extract a tar.gz using PharData in PHP, but it works only at a single level depth. I was thinking if some kind of recursion could make this work for multi-level depth.
$phar = new PharData('origin.tar.gz');
$phar->extractTo('/full/path'); // extract all files in the tar.gz
I have refined my code a bit and tried this, it works for multi-depth but fails when there is a directory(folder or nested folders) that also contains JSON. Can someone help me to extract them as well.
<?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)
?>
Thanks in advance.