php Ideas and Code Sharing for Exporting csv Format Data and Converting Numbers to Text
- 2021-06-28 12:05:25
- OfStack
php Export csv Format Data Implementation:
Define a string to store the content first, for example
$exportdata ='Rule 111, Rule 222, Review 222, Rule 222, Serve 2222, Rule 1, Rule 2, Rule 3, Match character, Set time, Validity period'.'n';
An foreach loop is then applied to the array where csv needs to be saved, for example
if (!empty($lists)){
foreach($lists as $key => $value){
$time = date("Y-m-d_H:i:s", $value['add_time']);
$exportdata .= "\"\t".$value['Rule_id']."\",\"\t".$value['Rule_name']."\",\"\t".$value['Matching_level']."\",\"\t"."{$value['Rule_action']}"."\",\"\t".$value['Service_type']."\",\"\t".$value['Keyword1']."\",\"\t".$value['Keyword2']."\",\"\t".$value['Keyword3']."\",\"\t".$value['Matching_word']."\",\"\t".$value['Set_time']."\",\"\t".$value['Validation_time']."\"\n";
}
}
The content in csv format is separated by','and can be separated in real time.One'n'can be split after each line.
Then the output will be executed later.for example
$filename = "plcnetinfo_{$date}.csv";
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$filename");
header("Expires: 0");
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
echo(mb_convert_encoding($exportdata,"gb2312","UTF-8"));
However, when exporting numbers, csv will remove the previous zero, for example, I want to show 00001, if the output will show 1. This solution is to output a'\"t', which is a tab that will display as a space.You can convert values into text.However,'''. will appear when importing, just use the trim function that comes with php once.The complete code is as follows:
//var_dump($sql);
$lists = $this->dbo->query($sql);
* $exportdata = ' rule 111, rule 222, Trial 222, gauge 222, clothes 2222, rule 1, rule 2, rule 3, Match Characters , Set time , Term of validity '."\n";
$date = date("YmdHis");
if (!empty($lists)){
foreach($lists as $key => $value){
$time = date("Y-m-d_H:i:s", $value['add_time']);
$exportdata .= "\"\t".$value['Rule_id']."\",\"\t".$value['Rule_name']."\",\"\t".$value['Matching_level']."\",\"\t"."{$value['Rule_action']}"."\",\"\t".$value['Service_type']."\",\"\t".$value['Keyword1']."\",\"\t".$value['Keyword2']."\",\"\t".$value['Keyword3']."\",\"\t".$value['Matching_word']."\",\"\t".$value['Set_time']."\",\"\t".$value['Validation_time']."\"\n";
}
}
$filename = "plcnetinfo_{$date}.csv";
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$filename");
header("Expires: 0");
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
echo(mb_convert_encoding($exportdata,"gb2312","UTF-8"));