php使用指定編碼導出mysql數(shù)據(jù)到csv文件的方法
更新時間:2015年03月31日 14:54:52 作者:不吃皮蛋
這篇文章主要介紹了php使用指定編碼導出mysql數(shù)據(jù)到csv文件的方法,涉及php查詢mysql及操作csv文件的技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了php使用指定編碼導出mysql數(shù)據(jù)到csv文件的方法。分享給大家供大家參考。具體實現(xiàn)方法如下:
<?php
/*
* PHP code to export MySQL data to CSV
*
* Sends the result of a MySQL query as a CSV file for download
* Easy to convert to UTF-8.
*/
/*
* establish database connection
*/
$conn = mysql_connect('localhost', 'login', 'pass') or die(mysql_error());
mysql_select_db('database_name', $conn) or die(mysql_error($conn));
mysql_query("SET NAMES CP1252");
/*
* execute sql query
*/
$query = sprintf('SELECT field1,field2 FROM table_name');
$result = mysql_query($query, $conn) or die(mysql_error($conn));
/*
* send response headers to the browser
* following headers instruct the browser to treat the data as a csv file called export.csv
*/
header('Content-Type: text/csv; charset=cp1252');
header('Content-Disposition: attachment;filename=output.csv');
/*
* output header row (if atleast one row exists)
*/
$row = mysql_fetch_assoc($result);
if ($row) {
echocsv(array_keys($row));
}
/*
* output data rows (if atleast one row exists)
*/
while ($row) {
echocsv($row);
$row = mysql_fetch_assoc($result);
}
/*
* echo the input array as csv data maintaining consistency with most CSV implementations
* - uses double-quotes as enclosure when necessary
* - uses double double-quotes to escape double-quotes
* - uses CRLF as a line separator
*/
function echocsv($fields)
{
$separator = '';
foreach ($fields as $field) {
if (preg_match('/\\r|\\n|,|"/', $field)) {
$field = '"' . str_replace('"', '""', $field) . '"';
}
echo $separator . $field;
$separator = ',';
}
echo "\r\n";
}
?>
希望本文所述對大家的php程序設(shè)計有所幫助。
您可能感興趣的文章:
- thinkPHP導出csv文件及用表格輸出excel的方法
- 基于php導出到Excel或CSV的詳解(附utf8、gbk 編碼轉(zhuǎn)換)
- PHP導出MySQL數(shù)據(jù)到Excel文件(fputcsv)
- 詳解PHP導入導出CSV文件
- php導出csv數(shù)據(jù)在瀏覽器中輸出提供下載或保存到文件的示例
- php導出csv格式數(shù)據(jù)并將數(shù)字轉(zhuǎn)換成文本的思路以及代碼分享
- PHP 導出數(shù)據(jù)到淘寶助手CSV的方法分享
- PHP實現(xiàn)CSV文件的導入和導出類
- PHP 實現(xiàn)從數(shù)據(jù)庫導出到.csv文件方法
- php導出CSV抽象類實例
- 原生PHP實現(xiàn)導出csv格式Excel文件的方法示例【附源碼下載】
相關(guān)文章
php array_flip() 刪除數(shù)組重復元素
在PHP中,用于刪除數(shù)組中重復元素有一個可用的函數(shù),那就是 array_unique(), 但是它并不是一個最高效的方法,使用array_flip() 函數(shù)將比array_uniqure()在速度上高出五倍左右。2009-01-01
PHP 5.3和PHP 5.4出現(xiàn)FastCGI Error解決方法
這篇文章主要介紹了PHP 5.3和PHP 5.4出現(xiàn)FastCGI Error解決方法,需要的朋友可以參考下2015-02-02
PHP使用strrev翻轉(zhuǎn)中文亂碼問題的解決方法
這篇文章主要介紹了PHP使用strrev翻轉(zhuǎn)中文亂碼問題的解決方法,通過自定義函數(shù)遍歷字符串并設(shè)置編碼格式解決亂碼問題,需要的朋友可以參考下2017-01-01
php實現(xiàn)的返回數(shù)據(jù)格式化類實例
這篇文章主要介紹了php實現(xiàn)的返回數(shù)據(jù)格式化類及其應(yīng)用實例,包括針對XML、JSON等的格式化,非常具有實用價值,需要的朋友可以參考下2014-09-09
is_uploaded_file函數(shù)引發(fā)的不能上傳文件問題
不能上傳文件,都返回失敗。經(jīng)過排查發(fā)現(xiàn)是PHP中的is_uploaded_file函數(shù)在搗鬼,下面是具體的處理方法,有類似情況的朋友可以參考下2013-10-10

