gags gags - 11 months ago 70
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

How do I extract this folder
in php and rename this file with random name to

Problem is that I can't use


since I don't have

Answer Source

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/";

$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']);