note 126387 added to function.deflate-add
| From: | ramesh dot jangid at eduvanz dot com | Date: | Sat, 04 Sep 2021 15:37:05 +0000 |
| Subject: | note 126387 added to function.deflate-add | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-216859@lists.php.net to get a copy of this message | ||
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();
}
----
Server IP: 45.112.84.4
Probable Submitter: 45.112.85.242 (proxied: 103.58.155.152)
----
Manual Page -- https://php.net/manual/en/function.deflate-add.php
Edit -- https://main.php.net/note/edit/126387
Del: integrated -- https://main.php.net/note/delete/126387/integrated
Del: useless -- https://main.php.net/note/delete/126387/useless
Del: bad code -- https://main.php.net/note/delete/126387/bad+code
Del: spam -- https://main.php.net/note/delete/126387/spam
Del: non-english -- https://main.php.net/note/delete/126387/non-english
Del: in docs -- https://main.php.net/note/delete/126387/in+docs
Del: other reasons-- https://main.php.net/note/delete/126387
Reject -- https://main.php.net/note/reject/126387
Search -- https://main.php.net/manage/user-notes.php