Home > Article > Backend Development > PHP exports csv format data and converts numbers into text solutions_PHP tutorial
PHP export of csv format data implementation:
First define a string to store the content, for example
$exportdata = 'Rule 111, Rule 222, Review 222, Regulation 222, Service 2222, Rule 1, Rule 2, Rule 3, match characters, set time, validity period'."n";
Then perform a foreach loop on the array that needs to be saved as csv, such as
if (!empty($lists)){
foreach($lists as $key => $value){
$time = date("Y-m-d_H:i:s", $value ['add_time']);
Since 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 ',', which can be separated in reality. Just an 'n' after each line can branch the line.
Then execute the output later. For example
$filename = "plcnetinfo_{$date}.csv";
position: attachment ; filename=$filename");
header("Expires: 0");
header("Pragma: public");
header("Cache-Control: must-revalidate, post-revalidate -check=0, pre-check=0");
header("Cache-Control: public");
echo(mb_convert_encoding($exportdata,"gb2312","UTF-8") );
But when exporting numbers, csv will remove the leading 0. For example, if I want to display 00001, if it is output, it will display 1. This solution is to use a '"t' when outputting, this is Tab characters will be displayed as spaces. The value can be converted into text. However, ' " ' will appear when importing. Just use the trim function that comes with PHP. The complete code is as follows:
, Rule 222, Service 2222, Rule 1, Rule 2, Rule 3, Match characters, set time, validity period '."n";
$date = date("YmdHis");
$ lists) {
FOREACH ($ lists as $ key = & gt; $ value) {
$ time = date ("y-m-d_h: 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";
";
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"));
http://www.bkjia.com/PHPjc/780022.html