PHP解压缩字符串

时间:2013-04-12 08:44:20

标签: php google-drive-api unzip

我正在通过API将Google Drive电子表格加载到PHP中。该请求返回XLSX电子表格,我需要解压缩它。为了节省我写一个临时的响应,然后调用,比如zip_open(),有没有办法可以将这样的方法传递给字符串?

3 个答案:

答案 0 :(得分:3)

我认为您最好的选择是创建一个临时文件然后解压缩。

// Create a temporary file which creates file with unique file name
$tmp = tempnam(sys_get_temp_dir(), md5(uniqid(microtime(true))));

// Write the zipped content inside
file_put_contents($tmp, $zippedContent);

// Uncompress and read the ZIP archive
$zip = new ZipArchive;
if (true === $zip->open($tmp)) {
    // Do whatever you want with the archive... 
    // such as $zip->extractTo($dir); $zip->close();
}

// Delete the temporary file
unlink($tmp);

答案 1 :(得分:1)

我自己写临时文件,但您可能希望在此处看到第一条评论:http://de3.php.net/manual/en/ref.zip.php


  

wdtemp at seznam dot cz   嗨,如果你有RAW CONTENT   只有一个字符串的ZIP文件,你不能在你的文件上创建文件   服务器(因为安全模式)能够创建一个文件   你可以传递给zip_open(),你会遇到困难   ZIP数据的未压缩内容。这可能会有所帮助:我写过   简单的ZIP解压缩功能,用于解压缩第一个文件   来自存储在字符串中的存档(无论它是什么文件)。它的   只是解析第一个文件的本地文件头,得到原始   该文件的压缩数据和该数据的解压缩(通常,   ZIP文件中的数据是通过'DEFLATE'方法压缩的,所以我们只是   通过gzinflate()函数解压缩它。)

<?php
function decompress_first_file_from_zip($ZIPContentStr){
//Input: ZIP archive - content of entire ZIP archive as a string
//Output: decompressed content of the first file packed in the ZIP archive
    //let's parse the ZIP archive
    //(see 'http://en.wikipedia.org/wiki/ZIP_%28file_format%29' for details)
    //parse 'local file header' for the first file entry in the ZIP archive
    if(strlen($ZIPContentStr)<102){
        //any ZIP file smaller than 102 bytes is invalid
        printf("error: input data too short<br />\n");
        return '';
    }
    $CompressedSize=binstrtonum(substr($ZIPContentStr,18,4));
    $UncompressedSize=binstrtonum(substr($ZIPContentStr,22,4));
    $FileNameLen=binstrtonum(substr($ZIPContentStr,26,2));
    $ExtraFieldLen=binstrtonum(substr($ZIPContentStr,28,2));
    $Offs=30+$FileNameLen+$ExtraFieldLen;
    $ZIPData=substr($ZIPContentStr,$Offs,$CompressedSize);
    $Data=gzinflate($ZIPData);
    if(strlen($Data)!=$UncompressedSize){
        printf("error: uncompressed data have wrong size<br />\n");
        return '';
    }
    else return $Data;
}

function binstrtonum($Str){
//Returns a number represented in a raw binary data passed as string.
//This is useful for example when reading integers from a file,
// when we have the content of the file in a string only.
//Examples:
// chr(0xFF) will result as 255
// chr(0xFF).chr(0xFF).chr(0x00).chr(0x00) will result as 65535
// chr(0xFF).chr(0xFF).chr(0xFF).chr(0x00) will result as 16777215
    $Num=0;
    for($TC1=strlen($Str)-1;$TC1>=0;$TC1--){ //go from most significant byte
        $Num<<=8; //shift to left by one byte (8 bits)
        $Num|=ord($Str[$TC1]); //add new byte
    }
    return $Num;
}
?> 

答案 2 :(得分:0)

查看zlib函数(如果在您的系统上可用)。据我所知,有zlib-decode(左右)之类的东西可以处理原始的zip数据。