php使用指定编码导出mysql数据到csv文件的方法
本文实例讲述了php使用指定编码导出mysql数据到csv文件的方法。分享给大家供大家参考。具体实现方法如下:
<?php
/*
*PHPcodetoexportMySQLdatatoCSV
*
*SendstheresultofaMySQLqueryasaCSVfilefordownload
*EasytoconverttoUTF-8.
*/
/*
*establishdatabaseconnection
*/
$conn=mysql_connect('localhost','login','pass')ordie(mysql_error());
mysql_select_db('database_name',$conn)ordie(mysql_error($conn));
mysql_query("SETNAMESCP1252");
/*
*executesqlquery
*/
$query=sprintf('SELECTfield1,field2FROMtable_name');
$result=mysql_query($query,$conn)ordie(mysql_error($conn));
/*
*sendresponseheaderstothebrowser
*followingheadersinstructthebrowsertotreatthedataasacsvfilecalledexport.csv
*/
header('Content-Type:text/csv;charset=cp1252');
header('Content-Disposition:attachment;filename=output.csv');
/*
*outputheaderrow(ifatleastonerowexists)
*/
$row=mysql_fetch_assoc($result);
if($row){
echocsv(array_keys($row));
}
/*
*outputdatarows(ifatleastonerowexists)
*/
while($row){
echocsv($row);
$row=mysql_fetch_assoc($result);
}
/*
*echotheinputarrayascsvdatamaintainingconsistencywithmostCSVimplementations
*-usesdouble-quotesasenclosurewhennecessary
*-usesdoubledouble-quotestoescapedouble-quotes
*-usesCRLFasalineseparator
*/
functionechocsv($fields)
{
$separator='';
foreach($fieldsas$field){
if(preg_match('/\\r|\\n|,|"/',$field)){
$field='"'.str_replace('"','""',$field).'"';
}
echo$separator.$field;
$separator=',';
}
echo"\r\n";
}
?>
希望本文所述对大家的php程序设计有所帮助。