Compress in-memory PHP array to a .tar.gz file (PHAR?)

2.7k Views Asked by At

I have a large in-memory array of xml-files as string.

I'm looking for the most efficient way to create a readable/extractable .tar.gz file from PHP (5.3).

Currently i'm using this class.

But :

  • It does not look maintained
  • It requires files (so i'm creating thousands of files from my memory array which are useless a few ms later)

So i'm looking for a efficient way to handle a .tar.gz file, most important point is to be able to easily put files in it with a simple command like :

$myArchive->putFileFromString($fileName, $dataString);

Looks like it is possible to configure PHAR with TAR & GZ, so it may be a solution?

$p = $p->convertToExecutable(Phar::TAR, Phar::GZ);

Bonus question, i am not sure if it would be better to build it live (after each xml string generation) to save memory, or just wait this huge object & compress it once. The ratio proc_usage / mem_usage is unclear to me in this case.

Target max usage is 100K XML files.

Thanks!

2

There are 2 best solutions below

1
On

It's a bit late, but for future reference :

You can create a tar.gz archive using the PharData class from the the phar extension. It's a bit like the ZipArchive, except that you can add content using the Array interface :

$archive = new PharData("outfile.tar");
foreach ($xmlfiles as $name => $data) {
    $archive[$name] = $data;
}

// compress to "outfile.tar.gz
$gzipped = $archive->compress(Phar::GZ);

// delete outfile.tar
unset($archive);
unlink("outfile.tar");
0
On

If you want to create tgz files, use PEAR's Archive_Tar package. It allows you to create tar + gz files on the fly from memory:

require_once 'Archive/Tar.php';
$t = new Archive_Tar('/path/to/dest.tar.gz', 'gz');
foreach ($xmlfiles as $key => $content) {
    $t->addString($key . '.xml', $content);
}