note 126387 deleted from function.deflate-add by cmb

From: Date: Sat, 04 Sep 2021 16:57:56 +0000
Subject: note 126387 deleted from function.deflate-add by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-216862@lists.php.net to get a copy of this message
Note Submitter: ramesh dot jangid at eduvanz dot com ---- Can be used while downloading CSV files in zipped format. function downloadCSV(& $query,& $header_mapping,& $filename) { $temp_directory = sys_get_temp_dir(); $csv_filename = tempnam($temp_directory, $filename); $shell_command = 'mysql \ --host="'.HOSTNAME.'" \ --user="'.USERNAME.'" \ --port="'.PORT.'" \ --password="'.PASSWORD.'" \ --database="'.DATABASE.'" \ --execute='.escapeshellarg($query).' | sed \'s/"/""/g;s/^/"/g;s/$/"/g;s/\t/","/g\' \ > '.escapeshellarg($csv_filename); shell_exec($shell_command); // execute shell command $handle = fopen($csv_filename, 'r'); if ($handle) { $data = fgetcsv($handle); if(count($data)==0) {echo 'No Records Found.';exit();} ob_end_clean(); header('Pragma: public'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Cache-Control: public'); header('Content-Description: File Transfer'); header('Content-type: application/octet-stream'); header('Content-Disposition: attachment; filename="'.$filename.'.csv.zip"'); header('Content-Transfer-Encoding: binary'); $gzip = deflate_init(ZLIB_ENCODING_GZIP, array('level' => 7)); $arr_headers = array(); $arr_cols_order = array(); foreach ($header_mapping as $col => $label) { $key = array_search($col, $data); $arr_headers[] = $label; $arr_cols_order[] = $key; } $header = '"Sr. No.","'.implode('","',$arr_headers).'"'.PHP_EOL; echo deflate_add($gzip, $header, ZLIB_NO_FLUSH); $i = 0; while (($data = fgetcsv($handle)) !== false) { $i++; $line_arr = array(); for($z=0,$z_count=count($arr_cols_order);$z<$z_count;$z++) { $index = $arr_cols_order[$z]; $line_arr[] = $data[$index]=='NULL' ? '' : str_replace('"','""',$data[$index]); } $line = '"'.$i.'","'.implode('","',$line_arr).'"'.PHP_EOL; echo deflate_add($gzip, $line, ZLIB_NO_FLUSH); } fclose($handle); unlink($csv_filename); echo deflate_add($gzip, '', ZLIB_FINISH); } exit(); }

« previous php.notes (#216862) next »