Home >Backend Development >PHP Tutorial >PHP uses open and fwrite to export files (code) in multiple formats
The content of this article is about PHP using open and fwrite to export files (code) in various formats. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .
<?php /** * Created by PhpStorm. * User: Jason0727 * Date: 2018/8/9 * Time: 14:48 */header("Content-Type: text/html;charset=utf-8");//定义文件名 $fileName = "测试文件名_" . date('YmdHis');//文件名中间不能有空格//文件名转码,以防乱码 $fileName = iconv('UTF-8','GBK',$fileName);///文件后缀 $ext = ".csv";//$ext = ".txt";//字段间的拼接符号// $dot = "|";$dot = ",";//打开文件句柄,记得赋权,否则报错 $fp = fopen("./files/" . $fileName . $ext,"a") or die("unable to open file!");//是否需要列表名称,0=>不需要 1需要,默认为1 $is_need_headerList = 1;//检测是否需要 headerListif($is_need_headerList == 1){ //定义列表名称 $headerList = ['列表1','列表2','列表3']; //初始化写入文件的字符串 $headerTxt = ""; //列表名称转码 foreach ($headerList as $v){ $headerTxt .= $v. $dot; } $headerTxt = rtrim($headerTxt,$dot)."\n"; //将列表名称写入文件句柄 fwrite($fp, $headerTxt); }//初始化数组数据$data = [ ['id'=>'值1','name'=>'值2','hobby'=>'值3'], ['id'=>'值11','name'=>'值22','hobby'=>'值33'], ['id'=>'值111','name'=>'值222','hobby'=>'值333'] ]; //循环写入数据//初始化数组的总数 $count = count($data);//循环次数 $limit = 0;foreach ($data as $v){ $limit++; $txt = $v['id'] .$dot . $v['name'] .$dot .$v['hobby']; if($count != $limit)//避免最后一次换行 $txt .= $dot .PHP_EOL; fwrite($fp,$txt); } fclose($fp);
$c = "测试•字符传换•五一快乐!";echo iconv('UTF-8','GBK//IGNORE',$c);//测试字符传换五一快乐!echo iconv('UTF-8','GBK',$c);//Detected an illegal character in input string
php implementation code for exporting Excel files in csv format
How PHP implements fuzzy query (graphic code)The above is the detailed content of PHP uses open and fwrite to export files (code) in multiple formats. For more information, please follow other related articles on the PHP Chinese website!