如何解压缩txt.gz文件并使用php存储到数据库中

时间:2013-01-22 04:59:40

标签: php mysql gzip unzip datafeed

我的zip文件名是Product_Catalog.txt.gz。这个zip文件包含一个txt文件。

如何提取并存储到我的数据库中

我已经在zip文件中解压缩并存储到我的数据库中。但我无法理解.gz格式。所以请告知

我的zip文件代码在这里

if (realpath($destinationname."/".$filename)){
    if ($zip = zip_open(realpath($directory."/".$filename)))
        {
            while (($zip_entry = zip_read($zip))){
            $zipfilename=zip_entry_name($zip_entry  );
            $zipfilename."<br>";
            $tmpfname = tempnam("/tmp", "");
            $handle = fopen($tmpfname, "w+");
            while($data = zip_entry_read($zip_entry,50000000000)){
            fwrite($handle,$data);
            }// end while $data
            fseek($handle,0);
            if ($separatetables);
            $table=strtok($zipfilename,"-");
            $sql="CREATE TABLE IF NOT EXISTS `$table` LIKE `cjfeeds`";
             mysql_query($sql);

如何将此代码转换为txt.gz

5 个答案:

答案 0 :(得分:2)

通常用于单个文件的

gzipZIP的文件格式不同。虽然两种格式都使用相同的压缩算法(DEFLATE),但标题完全不同,因此PHP的Zip函数无法识别您的文件。

相反,您可以使用compress.zlib:// wrapper打开gzip压缩文件。然后,您可以使用普通流函数来读取文件。

$handle = fopen("compress.zlib://$filename", 'r');

但是,有一些限制;例如,以读写模式打开gzip压缩文件是不可能的,寻求可能会很慢。如有必要,您可以通过制作临时未压缩副本来解决这些问题:

copy("compress.zlib://$filename", $tmpfname);

答案 1 :(得分:1)

您可以通过zlib module

的功能与.gz个文件进行互动

回应你的评论:

您不需要执行while($zip_entry = zip_read($zip)),因为gz文件中不包含多个文件。 .gz文件只是一个已压缩的文件。不幸的是,这也意味着也没有等同于zip_entry_name,因为只有一个文件。

如果你正在尝试阅读tarball - 已经连接在一起并压缩形成.tar.gz文件的文件存档 - 那么Zlib不适合你,因为它不是设计的处理这个问题。你会想要PharData之类的东西:

$phar = new PharData($filename);
foreach ($phar as $phar_stream) {
  $file_data = file_get_contents($phar_stream);
  // process $file_data how you like
}

如果这些只是单文件gz文件,那么您可以使用通常文件系统函数的gz版本来读取文件。

您可以使用gzread按照当前使用zip_entry_read的方式处理文件块,也可以使用gzfile将所有行读入数组。有一个readgzfile函数可以抓取整个文件,但遗憾的是它似乎只是将输出直接转储到客户端,而不是执行文件。你可以使用输出缓冲来捕获输出,但考虑到你的其他选择,这似乎太麻烦了。

答案 2 :(得分:1)

你一直称它为zip文件。它不是zip文件(.zip)。这是一个gzip文件(.gz)。格式不同。

您可以使用gzdecode()解压缩gzip文件。

答案 3 :(得分:1)

你不提取。

if ($rrpath){
     if ($zip = gzopen($rrpath, "rb"))
        {   
            $filenamen = $_SESSION['files_list'][$i];       
            $zipfilename = str_replace('.gz', '', $_SESSION['files_list'][$i]); 
            $tmpfname = tempnam("/home/demoosiz/tmp", "");      
            $handle = fopen($tmpfname, "w+");
            ini_set("max_execution_time",3000000000000);
            while($data = gzread($zip, 4096)){
            fwrite($handle,$data);
            }// end while $data
            fseek($handle,0);
            if ($separatetables);
            $table=strtok($zipfilename,"-");                   
           // $sqly = "TRUNCATE TABLE `cjfeeds`";
            //mysql_query($sqly);                           
             // I'm not too sure if this is windows specific
            $tmpfile=addslashes($tmpfname);
            //if the script times out uncomment the next line 
             ini_set("max_execution_time",3000000000000);
            $sql22 ="LOAD DATA LOCAL INFILE '$tmpfile' REPLACE  INTO TABLE `cjfeeds` FIELDS TERMINATED BY '$fieldseparator' IGNORE 1 LINES;";

您可以使用此代码。这段代码对你很有帮助。

答案 4 :(得分:1)

试试这个......

if(isset($_FILES['zipfile'])) 
{

    $filename = $_FILES['zipfile']['name'];
    $source = $_FILES['zipfile']['tmp_name'];
    $type = $_FILES['zipfile']['type'];

    /*$name = explode('.zip', $filename); # $name[0] returns the name of the file. $name[1] returns the extension (zip)

    ; */ # Where the file will be saved. I.E. 'extracted/myFile-02151985/'
    $target = PHYSICAL_PATH."upload/";
    // Ensures that the correct file type was chosen.
    $accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
    foreach($accepted_types as $mime_type)
    {
        if($mime_type == $type)
        {
            $okay = true;
            break;
        } 
    }

    $okay = strtolower($name[1]) == 'zip' ? true : false;

    if(!$okay) 
    {
        $msg="Please choose a zip file, dummy!";
    }
    $saved_file_location = $target.$filename;
    if(move_uploaded_file($source, $target . $filename))
    {
        global $target;
        global $unique_folder;
        $zip = new ZipArchive();
            $x = $zip->open($saved_file_location);
            if ($x === true) 
            {
                $folder=$zip->extractTo($target);
                for ( $i=0; $i < $zip->numFiles; $i++ ) 
                { 
                    echo $entry = $zip->getNameIndex($i); 
                    $filename=explode('/',$entry);
                    print_r($filename);
                    if($filename[1] != '')
                    { 
                        $filename_folder=$filename[0];
                        $filename = $filename[1]; //

                        $name = explode('.zip', $filename_folder); # $name[0] returns the name of the file. $name[1] returns the extension (zip)
                        //echo 'sfkdf'.$name[0];
                        $target = PHYSICAL_PATH."upload/";

                        $sql = "select `id` from `tracks` order by `id` desc";
                            $list = mysql_query($sql);
                            $list_num = mysql_num_rows($list);
                            if($list_num > 0)
                            {

                            $res = mysql_fetch_array($list);
                            $new_id=$res['id'];
                            } else {
                            $new_id=1;
                            }
                        $check_for_jpg = strpos($filename, '.mp3');

                        if ($check_for_jpg === false ){
                            echo 'Check file format.';
                            $source=$target . $name[0].'/'.$filename;
                            unlink($source);
                        } else {
                            $srch = array(' ','--','&quot;','!','@','#','$','%','^','&','*','(',')','_','+','{','}','|',':','"','<','>','?','[',']','\\',';',"'",',','/','*','+','~','`','=');
                            $rep = array('_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_');
                            $name_song[$i]= str_replace($srch,$rep,$filename);
                            $title_name=explode('.',$filename);

                            $new_id=$new_id+1;
                            $new_filename=$new_id.'-'.$name_song[$i];
                            mysql_query("insert into `tracks` set track='".addslashes(stripslashes($new_filename))."',title='".addslashes(stripslashes($title_name[0]))."',tape_id='".$id_last."',addDate=NOW(),status=1 ");
                            $source=$target . $name[0].'/'.$filename; $target_move=$target.$new_filename;
                            if(rename($source,$target_move)) { unlink($source); } else { echo 'not';}
                            echo 'folder zip';
                            echo '<li>' . $new_filename . '</li>';
                        }
                        rmdir($target . $name[0]);
                    }
                    else { echo $target = PHYSICAL_PATH."upload/";
                        $sql = "select `id` from `test_table` order by `id` desc";

                        $list = mysql_query($sql);
                        $list_num = mysql_num_rows($list);
                        if($list_num > 0) {
                        //and, instead of using "while":
                        $res = mysql_fetch_array($list); // will return the highest "id" number
                        echo $new_id=$res['id'];
                        } else {
                        $new_id=1;
                        }

                        $check_for_jpg = strpos($entry, '.mp3');

                        if ($check_for_jpg === false ){
                            echo 'Check file format.';
                            $source=$target .$entry;
                            unlink($source);
                        } else {
                            $srch = array(' ','--','&quot;','!','@','#','$','%','^','&','*','(',')','_','+','{','}','|',':','"','<','>','?','[',']','\\',';',"'",',','/','*','+','~','`','=');
                            $rep = array('_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_');
                            $name_song[$i]= str_replace($srch,$rep,$entry);
                            $title_name=explode('.',$entry);
                            $new_id=$new_id+1;
                            $new_filename=$new_id.'-'.$name_song[$i];
                            mysql_query("insert into `tracks` set track='".addslashes(stripslashes($new_filename))."',title='".addslashes(stripslashes($title_name[0]))."',tape_id='".$id_last."',status=1 ");
                            $source=$target .$entry; $target_move=$target.$new_filename;
                            if(rename($source,$target_move)) { unlink($source); } else { echo 'not';}
                            echo 'only zip';
                            echo '<li>' . $new_filename . '</li>';
                        }

                    }
                }
                $zip->close();
                unlink($saved_file_location); #deletes the zip file. We no longer need it.
            } else {
                die("There was a problem. Please try again!");
            }

    } else {
        $msg="There was a problem";
    }
}