Search code examples
phpmacoswidgetibooksphp-ziparchive

Archive a .wdgt folder in ZipArchive()


I'm creating a online widget creation tool in PHP, and I am able to export everything I need via .zip , just the problem is that users have to extract the zip and then add the .wdgt extension on the folder for it to work in iBooks. Is there any way I could make this part of the process easier, e.g - just unzip and the .wdgt folder is there, or even better, download as .wdgt.

Here is the code I have to create a ZIP file:

//zip name
$archiveName = 'widget.zip';
$fileNames = array();

//scan through directories, and add to array
foreach(scandir($workingDir) as $content){
    $fileNames[] = $workingDir.$content;
}
foreach(scandir($resources) as $content){
    $fileNames[] = $resources.$content;
}

archiveFiles($fileNames, $archiveName);

function archiveFiles($fileNames, $archiveName){
    //init new ZipArchive()
    $zip = new ZipArchive();
    //open archive
    $zip->open($archiveName);       
    if($zip->open($archiveName, ZIPARCHIVE::OVERWRITE ) !==TRUE){
        exit("Cannot open <$archiveName>\n");
    }
    else{
        //archive create, now add files
        foreach($fileNames as $files){
            if('.' === $files || '..' === $files) continue;     
            //get just the filename and extension
            $fileName = explode("/", $files);
            $num = (count($fileName) - 1);
            $theFilename = $fileName[$num]; 
            //add file into the archive - full path of file, new filename
            $zip->addFile($files,$theFilename);         
        }
        $zip->close();
        header( 'Location: http://MYURL/'.$archiveName ) ; //Redirects to the zip archive
        exit;
    }
}

This works fine. I just need to be able to either just download a .wdgt folder with the content I need in it, or be able to ZIP up a .wdgt folder that has the content that I need.

I have tried changing $archiveName to $archiveName = "widget.wdgt.zip"; and $archiveName = "widget.wdgt";

The $archiveName = "widget.wdgt.zip"; was able to unzip fine on Windows. Although on the MAC is just gave an error. And It has to work on the MAC as it is in iBook's Author these widgets will work on


Solution

  • Managed to get a .wdgt folder downloaded within a zip file, all that I needed to do was when adding the file in the loop was this:

    $zip->addFile($files, 'MYWIDGET.wdgt/'.$theFilename);
    

    by adding the 'MYWIDGET.wdgt/'.$theFilename path into the addFile() it forced ZipArchive to create a MYWIDGET.wdgt folder and adding the files into it.