【问题标题】:how to unzip txt.gz file and store into database using php如何解压缩txt.gz文件并使用php存储到数据库中
【发布时间】:2013-01-05 06:53:32
【问题描述】:

我的 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

【问题讨论】:

  • 您实际上有两个问题。第一个问题:如何使用 PHP 提取 .gz 存档的内容。第二个问题:如何将专有文件格式导入 MySQL 数据库。我建议你分开问这些问题。

标签: php mysql gzip unzip datafeed


【解决方案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 函数可以抓取整个文件,但不幸的是,它似乎只是将输出直接转储到客户端,而不是做一个文件。您可以使用输出缓冲来捕获该输出,但考虑到您的其他选项,这似乎太麻烦了。

【讨论】:

  • 嗨,如何将这个 while (($zip_entry = zip_read($zip))) 更改为 gz while。我的意思是这个while循环被读取文件的所有行并存储到数据库中。我怎样才能改成.gz读入while
  • @SomethingWrong 我已经更新了我的答案以回复您的评论。
【解决方案2】:

gzip,一般用于单个文件,与ZIP的文件格式不同。虽然两种格式都使用相同的压缩算法 (DEFLATE),但标题完全不同,因此 PHP 的 Zip 函数将无法识别您的文件。

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

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

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

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

【讨论】:

  • +1。你的回答比我的简单多了。我忘了有一个流包装器。
【解决方案3】:

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

你可以使用gzdecode()来解压一个gzip文件。

【讨论】:

    【解决方案4】:

    你不提取。

    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;";
    

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

    【讨论】:

      【解决方案5】:

      试试这个....

      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";
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2018-12-02
        • 1970-01-01
        • 2021-10-02
        • 2012-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-15
        • 1970-01-01
        相关资源
        最近更新 更多