James
James

Reputation: 43647

Working with files and folders using ZIP

We have some html code like:

<body>Some text</body>

And a variable $contents.

Its first time I work with zip in php, have a couple of questions.

How do I:

  1. create a folder named HTML and place it inside $contents (no real creation on ftp, just in variable)

  2. create an index.html and place it inside HTML folder, which is inside $contents

    So the $contents before zip should contain:

     /HTML/index.html (with <body>Some text</body> code inside)
    
  3. create a zip archive with all the content inside $contents variable.

Upvotes: 2

Views: 152

Answers (2)

Havelock
Havelock

Reputation: 6968

I would suggest using the ZipArchive class. So you could have something like this

$html = '<body>some HTML</body>';
$contents = new ZipArchive();
if($contents->open('html.zip', ZipArchive::CREATE)){
    $contents->addEmptyDir('HTML');
    $contents->addFromString('index.html', $html);
    $contents->close()
}

Upvotes: 0

Jay
Jay

Reputation: 3305

If I understand you correctly:

$contents = '/tmp/HTML';
// Make the directory
mkdir($contents);
// Write the html
file_put_contents("$contents/index.html", $html);
// Zip it up
$return_value = -1;
$output = array();
exec("zip -r contents.zip $contents 2>&1", $output, $return_value);
if ($return_value === 0){
    // No errors
    // You now have contents.zip to play with
} else {
   echo "Errors!";
   print_r($output);
}

I'm not using a library to zip it, just the command line, but you could use a library if you wished (but I am checking to see if zip executed correctly).


If you really want to do everything truly in memory, you can do this:

$zip = new ZipArchive;
if ($zip->open('contents.zip') === TRUE) {
    $zip->addFromString('contents/index.html', $html);
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}

http://www.php.net/manual/en/ziparchive.addfromstring.php

Upvotes: 1

Related Questions