首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP在shell中的'gzuncompress‘函数?

PHP在shell中的'gzuncompress‘函数?
EN

Stack Overflow用户
提问于 2012-02-07 21:51:20
回答 1查看 3.3K关注 0票数 0

可能重复: 放气命令行工具

是的,我知道我可以在shell上使用PHP本身,但是我需要在PHP可用之前部署的脚本中使用这个功能。

我尝试过gzipunzip,但是要么我的参数不正确,要么它们不使用相同的压缩。

我想在bash脚本中使用这个。进入更高级别的脚本语言不是一种选择。

为了测试目的,我编写了以下PHP脚本:

代码语言:javascript
复制
#!/usr/bin/php
<?
  $contents = file_get_contents( $argv[1] );
  $data = gzuncompress( $contents );
  echo substr( $data, 0, 20 ) . "\n";
?>

这将输出我期望的结果(解码数据的开始)。

如果我将相同的文件传递给gunzip

代码语言:javascript
复制
$ gunzip -c data
gzip: data: not in gzip format

如果我尝试unzip

代码语言:javascript
复制
$ unzip data
Archive:  data
  End-of-central-directory signature not found.  Either this file is not
  a zipfile, or it constitutes one disk of a multi-part archive.  In the
  latter case the central directory and zipfile comment will be found on
  the last disk(s) of this archive.
unzip:  cannot find zipfile directory in one of data2 or
        data2.zip, and cannot find data2.ZIP, period.

正如建议的那样,并且考虑到没有其他实用的方法,我采用了相关问题中提出的解决方案。

但考虑到我希望避免使用另一种脚本语言(并引入另一种依赖项),我支持所有这些脚本语言:

代码语言:javascript
复制
_uncompressedData=
if hash perl 2>&-; then
  echo "Using Perl for decompression..." >&2
  _uncompressedData=$(perl -MCompress::Zlib -e 'undef $/; print uncompress(<>)' < compressed.bin || true)
elif hash ruby 2>&-; then
  echo "Using Ruby for decompression..." >&2
  _uncompressedData=$(ruby -rzlib -e 'print Zlib::Inflate.new.inflate(STDIN.read)' < compressed.bin || true)
elif hash php 2>&-; then
  echo "Using PHP for decompression..." >&2
  _uncompressedData=$(php -r "echo gzuncompress(file_get_contents('php://stdin'));" < compressed.bin || true)
elif hash python 2>&-; then
  echo "Using Python for decompression..." >&2
  _uncompressedData=$(python -c "import zlib,sys;print zlib.decompress(sys.stdin.read())" < compressed.bin || true)
else
  echo "Unable to find decompressor!" >&2
  exit 1
fi

这4个版本与我的测试用例产生了完全相同的输出。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-02-07 22:22:41

gzuncompress期望的格式是不带gzip头的原始zlib格式。如果使用zlib库的C,默认情况下会使用这种格式。

您可以使用zpipe命令行实用程序解压缩这种格式。此实用程序的源代码可在examples/zpipe.c中的zlib源代码发行版中找到。但默认情况下,该程序没有编译和安装。没有广泛部署的接受原始zlib格式的命令行实用程序。

如果您想使用PHP的gzip格式( gzipgunzip处理的友好头),那么您需要使用gzencode & gzdecode,而不是gzcompress & gzuncompress

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9184546

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档