gags
gags

Reputation: 345

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.

Upvotes: 3

Views: 1536

Answers (1)

Cristofor
Cristofor

Reputation: 2097

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();                   
}

Upvotes: 3

Related Questions