php生成CSV格式(转)

参考网址: 
php对csv文件的常用操作集合 
http://blog.xhbin.com/archives/748

1,下载CSV格式文档 
唯一需要特别注意的是编码。

 <?
include_once("conn/conn.php");//连接数据库 $EXCEL_OUT="id,title,info\n";//生成字段 $query="select * from tb_info";//需要生成的数据查询语句
$result=mysql_query($query);
while($ROW=mysql_fetch_array($result))
{
$id=$ROW["id"];
$title=$ROW["title"];
$content=$ROW["content"]; $EXCEL_OUT.=iconv('UTF-8','GB2312',"$id,$title,$content\n");
} header("Content-type:text/csv");
header("Content-Disposition:attachment;filename=生成文件名称.csv"); //“生成文件名称”=自定义
header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
header('Expires:0');
header('Pragma:public');
echo $EXCEL_OUT;
?>

2,生成.csv文件(不下载)

 $action = $_GET['action'];
if ($action=='make'){
$fp = fopen("csv.csv","a"); //打开csv文件,如果不存在则创建
$data_arr1 = array("","","","","公司"); //第一行数据
$data_arr2 = array("","","","","中午"); //第二行数据
$data_str1 = implode(",",$data_arr1); //用 ' 分割成字符串
$data_str2 = implode(",",$data_arr2); //用 ' 分割成字符串
$data_str = $data_str1."\r\n".$data_str2."\r\n"; //加入换行符 fwrite($fp,iconv('UTF-8','GB2312',$data_str)); //写入数据
fclose($fp); //关闭文件句柄
echo "生成成功";
}
echo "<br>";
echo "<a href='?action=make'>生成csv文件</a>"; //批注:由于涉及文件读写,所以有权限要求。比如通过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)

上一篇:Delphi 之 定时器 (TTimer组件)


下一篇:document与window的区别