php导出CSV文件的简单示例

发布时间:2020-01-26编辑:脚本学堂
分享一段php导出csv文件的代码,很简单,使用php header函数来实现csv文件的导出,有需要的朋友参考下。

用php代码导出CSV文件,如下:
 

复制代码 代码示例:

<?php
/**
* 导出csv文件,header函数示例
* edit: www.jb200.com
*/
header( "Cache-Control: public" );
header( "Pragma: public" );
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:attachment;filename=txxx.csv");
header('Content-Type:APPLICATION/OCTET-STREAM');

ob_start();
$header_str =  iconv("utf-8",'gbk',"信息id,标题,名称,电话,QQ,Email,内容,时间n");
$file_str="";
 
$mysqli= new mysqli('localhost','root','','test');

if (mysqli_connect_errno()) {
    printf("Connect failed: %sn", mysqli_connect_error());
    exit();
}
$sql='select *  from messages';
$mysqli->query("set names utf8 ;");
$result=$mysqli->query($sql);

if($result){
while ($row = mysqli_fetch_assoc($result)){
    $file_str.= $row['id'].','.$row['title'].','.$row['name'].','."'{$row['telephone']}'".','.$row['qq'].','.$row['email'].','.str_ireplace(',',',',$row['content']).','.$row['retime']."n";
}
}else{
 echo "nonono!!!";
}
$file_str=  iconv("utf-8",'gbk',$file_str);
ob_end_clean();
echo $header_str;
echo $file_str;
?>