php生成CSV格式(转)
参考网址:
php对csv文件的常用操作集合
http://blog.xhbin.com/archives/748
1,下载CSV格式文档
唯一需要特别注意的是编码。
1 <? 2 include_once("conn/conn.php");//连接数据库 3 4 $EXCEL_OUT="id,title,info\n";//生成字段 5 6 $query="select * from tb_info";//需要生成的数据查询语句 7 $result=mysql_query($query); 8 while($ROW=mysql_fetch_array($result)) 9 { 10 $id=$ROW["id"]; 11 $title=$ROW["title"]; 12 $content=$ROW["content"]; 13 14 $EXCEL_OUT.=iconv('UTF-8','GB2312',"$id,$title,$content\n"); 15 } 16 17 header("Content-type:text/csv"); 18 header("Content-Disposition:attachment;filename=生成文件名称.csv"); //“生成文件名称”=自定义 19 header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 20 header('Expires:0'); 21 header('Pragma:public'); 22 echo $EXCEL_OUT; 23 ?>
2,生成.csv文件(不下载)
1 $action = $_GET['action']; 2 if ($action=='make'){ 3 $fp = fopen("csv.csv","a"); //打开csv文件,如果不存在则创建 4 $data_arr1 = array("10001","10002","10003","10004","公司"); //第一行数据 5 $data_arr2 = array("20001","20002","20003","20004","中午"); //第二行数据 6 $data_str1 = implode(",",$data_arr1); //用 ' 分割成字符串 7 $data_str2 = implode(",",$data_arr2); //用 ' 分割成字符串 8 $data_str = $data_str1."\r\n".$data_str2."\r\n"; //加入换行符 9 10 fwrite($fp,iconv('UTF-8','GB2312',$data_str)); //写入数据 11 fclose($fp); //关闭文件句柄 12 echo "生成成功"; 13 } 14 echo "<br>"; 15 echo "<a href='?action=make'>生成csv文件</a>"; 16 17 18 //批注:由于涉及文件读写,所以有权限要求。比如通过http方式是无法创建该文件的。(可以通过php file.php方式)
附:iconv 用法
string iconv ( string $in_charset , string $out_charset , string $str )
iconv — Convert string to requested character encoding
参数:
1,in_charset 输入字符串的编码
2,out_charset 输出字符串的编码
If you append the string //TRANSLIT to out_charset transliteration is activated. This means that when a character can't be represented in the target charset, it can be approximated through one or several similarly looking characters. If you append the string //IGNORE, characters that cannot be represented in the target charset are silently discarded. Otherwise, str is cut from the first illegal character and an E_NOTICE is generated.
3,str 被转码的字符串
返回值:
返回转码后的字符串或false(返回失败时)。
可能会用到两个可选的辅助参数:IGNORE和TRANSLIT
例如:iconv("UTF-8","GB2312//IGNORE",$data)