【问题标题】:How to uncompress a tar.gz string如何解压缩 tar.gz 字符串
【发布时间】:2012-12-18 20:50:46
【问题描述】:
我有一个字符串,它是 tar.gz 压缩文件的内容(如果有的话,文件名应该是 tar.gz)。它以 JSON 格式传递给我,字符串是 base64 编码的。
我已经设法从 base64 解码字符串,现在剩下一个 tar.gz 字符串。有谁知道我可以在不创建临时文件然后使用 system('tar -zxvf ...') 的情况下将其提取到内存中的方法?它认为这样做确实会浪费资源,但是如果我无法弄清楚,我想我将不得不创建一个文件并使用 system()。
里面只有一个文件(xml文件),所以它不是多个文件。
【问题讨论】:
标签:
php
tar
gzip
compression
【解决方案1】:
您可以使用proc_open 和管道将文件流式传输到 tar 的标准输入。这是一个来自 php.net 的稍微改编的示例
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("file", "/tmp/error-output.txt", "a") // stderr is a file to write to
);
$process = proc_open('tar xz', $descriptorspec, $pipes, __DIR__, $env);
if (is_resource($process)) {
// $pipes now looks like this:
// 0 => writeable handle connected to child stdin
// 1 => readable handle connected to child stdout
// Any error output will be appended to /tmp/error-output.txt
fwrite($pipes[0], $tar_gz_string);
fclose($pipes[0]);
echo stream_get_contents($pipes[1]);
fclose($pipes[1]);
proc_close($process);
}