Home > php教程 > php手册 > body text

php导出csv格式文件

WBOY
Release: 2016-06-10 15:07:35
Original
923 people have browsed it

因为要为公司导出一份数据,查找了很多资料,很多看不懂,很多还存在编码问题,乱七八槽的,这份资料虽然也是借鉴的,不过

因为用起来方便,所以自己保留一份!

export_csv();
function export_csv() {
$filename = date('YmdHis').".csv";//文件名
header("Content-type:text/csv");
header("Content-Disposition:attachment;filename=".$filename);
header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
header('Expires:0');
header('Pragma:public');
echo array_to_string(get_export_data());
}
function array_to_string($result) {
if(empty($result)) {
return i("没有符合您要求的数据!^_^");
}
$data = '书ID,书名'."\n"; //栏目名称
$size_result = sizeof($result);
for($i = 0 ; $i $data .= i($result[$i]['name']).','.i($result[$i]['option'])."\n";
}
return $data;
}
function get_export_data() {
$link = mysql_connect('localhost','root','121051xz') or die(mysql_error());
mysql_select_db('ht');
mysql_query("set names 'utf8'");//定义编码
$sql = 'select * from booklist';
$result = mysql_query($sql);
$rowaa = mysql_fetch_array($result);
$res = array();
$i = 0;
while($row = mysql_fetch_array($result)) {
$res[$i]['name'] = $row['bookid'];
$res[$i]['option'] = $row['bookname'];
$i++;
}
return $res;
}
function i($strInput) {
return iconv('utf-8','gb2312',$strInput);//页面编码为utf-8时使用,否则导出的中文为乱码
}

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!