php使用指定編碼導(dǎo)出mysql數(shù)據(jù)到csv文件的方法
更新時(shí)間:2015年03月31日 14:54:52 作者:不吃皮蛋
這篇文章主要介紹了php使用指定編碼導(dǎo)出mysql數(shù)據(jù)到csv文件的方法,涉及php查詢mysql及操作csv文件的技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
本文實(shí)例講述了php使用指定編碼導(dǎo)出mysql數(shù)據(jù)到csv文件的方法。分享給大家供大家參考。具體實(shí)現(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"; } ?>
希望本文所述對(duì)大家的php程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:
- thinkPHP導(dǎo)出csv文件及用表格輸出excel的方法
- 基于php導(dǎo)出到Excel或CSV的詳解(附utf8、gbk 編碼轉(zhuǎn)換)
- PHP導(dǎo)出MySQL數(shù)據(jù)到Excel文件(fputcsv)
- 詳解PHP導(dǎo)入導(dǎo)出CSV文件
- php導(dǎo)出csv數(shù)據(jù)在瀏覽器中輸出提供下載或保存到文件的示例
- php導(dǎo)出csv格式數(shù)據(jù)并將數(shù)字轉(zhuǎn)換成文本的思路以及代碼分享
- PHP 導(dǎo)出數(shù)據(jù)到淘寶助手CSV的方法分享
- PHP實(shí)現(xiàn)CSV文件的導(dǎo)入和導(dǎo)出類
- PHP 實(shí)現(xiàn)從數(shù)據(jù)庫(kù)導(dǎo)出到.csv文件方法
- php導(dǎo)出CSV抽象類實(shí)例
- 原生PHP實(shí)現(xiàn)導(dǎo)出csv格式Excel文件的方法示例【附源碼下載】
相關(guān)文章
PHP使用trim函數(shù)去除字符串左右空格及特殊字符實(shí)例
這篇文章主要介紹了PHP使用trim函數(shù)去除字符串左右空格及特殊字符的用法,結(jié)合實(shí)例簡(jiǎn)單分析了trim函數(shù)不帶附加參數(shù)去除空格及使用附加參數(shù)去除指定字符的使用技巧,需要的朋友可以參考下2016-01-01關(guān)于url地址傳參數(shù)時(shí)字符串有回車造成頁(yè)面腳本賦值失敗的解決方法
本篇文章是對(duì)關(guān)于url地址傳參數(shù)時(shí)字符串有回車造成頁(yè)面腳本賦值失敗的解決方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06php簡(jiǎn)單生成一組與多組隨機(jī)字符串的方法
這篇文章主要介紹了php簡(jiǎn)單生成一組與多組隨機(jī)字符串的方法,涉及php基于rand方法的隨機(jī)字符串相關(guān)操作技巧,需要的朋友可以參考下2017-05-05PHP基于PDO調(diào)用sqlserver存儲(chǔ)過(guò)程通用方法【基于Yii框架】
這篇文章主要介紹了PHP基于PDO調(diào)用sqlserver存儲(chǔ)過(guò)程通用方法,結(jié)合實(shí)例形式分析了基于Yii框架采用pdo調(diào)用sqlserver存儲(chǔ)過(guò)程的相關(guān)操作步驟與實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-10-10