gags gags - 1 month ago 19
PHP Question

Extract a file from a zip archive then rename it

I have this file that gets downloaded at:

DownloadFile($reportDownloadUrl, $DownloadPath);


But it's a zip file. Inside of it, a CSV file gets created with a random name i.e
random_name.csv


How do I extract this folder
abc.zip
in php and rename this file with random name to
new_name.csv


Problem is that I can't use

$zip->renameName('currentname.csv','newname.csv');


since I don't have
currentname
.

Answer

This code inspects the file in zipLocation then iterates over them to check if there are csv files. If it finds something it copies inside the directory with its original name, then copies another copy with a new name.

$zipLocation = "path/to/file.zip";

$zip = new ZipArchive;

if ($zip->open($zipLocation) === true) {
    for($i = 0; $i < $zip->numFiles; $i++) {
        $filename = $zip->getNameIndex($i);
        if (pathinfo($filename, PATHINFO_EXTENSION)=="csv"){
            $fileinfo = pathinfo($filename);
            copy("zip://".$zipLocation."#".$filename, "./newname.csv");
            copy("zip://".$zipLocation."#".$filename, "./".$fileinfo['basename']);
        }
    }                   
    $zip->close();                   
}
Comments