php生成CSV格式

作者:zccst

参考网址:
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("10001","10002","10003","10004","公司"); //第一行数据
$data_arr2 = array("20001","20002","20003","20004","中午"); //第二行数据
$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)


如果您觉得本文的内容对您的学习有所帮助,您可以微信:
[img]http://dl2.iteye.com/upload/attachment/0109/0668/fb266dfa-95ca-3d09-b41e-5f04a19ba9a1.png[/img]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值