国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數據庫 > MySQL > 正文

php使用指定編碼導出mysql數據到csv文件的方法

2024-07-24 12:43:23
字體:
來源:轉載
供稿:網友

這篇文章主要介紹了php使用指定編碼導出mysql數據到csv文件的方法,涉及php查詢mysql及操作csv文件的技巧,具有一定參考借鑒價值,需要的朋友可以參考下

本文實例講述了php使用指定編碼導出mysql數據到csv文件的方法。分享給大家供大家參考。具體實現方法如下:

  1. <?php 
  2. /* 
  3.  * PHP code to export MySQL data to CSV 
  4.  *  
  5.  * Sends the result of a MySQL query as a CSV file for download 
  6.  * Easy to convert to UTF-8. 
  7.  */ 
  8.   
  9.  /* 
  10.  * establish database connection 
  11.  */ 
  12.   
  13. $conn = mysql_connect('localhost''login''pass'or die(mysql_error()); 
  14. mysql_select_db('database_name'$connor die(mysql_error($conn)); 
  15. mysql_query("SET NAMES CP1252"); 
  16. /*  
  17.  * execute sql query    
  18.  */ 
  19. $query = sprintf('SELECT field1,field2 FROM table_name'); 
  20. $result = mysql_query($query$connor die(mysql_error($conn)); 
  21. /*  
  22.  * send response headers to the browser 
  23.  * following headers instruct the browser to treat the data as a csv file called export.csv 
  24.  */ 
  25. header('Content-Type: text/csv; charset=cp1252'); 
  26. header('Content-Disposition: attachment;filename=output.csv'); 
  27. /*  
  28.  * output header row (if atleast one row exists)  
  29.  */ 
  30.     
  31. $row = mysql_fetch_assoc($result);  
  32. if ($row) { 
  33.   echocsv(array_keys($row)); 
  34.   
  35. /* 
  36.  * output data rows (if atleast one row exists) 
  37.  */ 
  38. while ($row) { 
  39.   echocsv($row); 
  40.   $row = mysql_fetch_assoc($result); 
  41.   
  42. /* 
  43.  * echo the input array as csv data maintaining consistency with most CSV implementations 
  44.  * - uses double-quotes as enclosure when necessary 
  45.  * - uses double double-quotes to escape double-quotes 
  46.  * - uses CRLF as a line separator 
  47.  */ 
  48.   
  49. function echocsv($fields
  50.   $separator = ''
  51.   foreach ($fields as $field) { 
  52.     if (preg_match('///r|//n|,|"/'$field)) { 
  53.  $field = '"' . str_replace('"''""'$field) . '"'
  54.     } 
  55.     echo $separator . $field
  56.     $separator = ','
  57.   } 
  58.   echo "/r/n"
  59. ?> 

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 康马县| 阿勒泰市| 镇平县| 修文县| 乡城县| 广宁县| 邹平县| 肥东县| 旬阳县| 汤阴县| 邢台县| 富锦市| 罗山县| 项城市| 肇州县| 准格尔旗| 盐山县| 永州市| 禹州市| 河间市| 宜良县| 罗源县| 谢通门县| 岢岚县| 松滋市| 巩留县| 河南省| 调兵山市| 湘潭县| 安丘市| 龙陵县| 上虞市| 塔河县| 西贡区| 双江| 三门峡市| 高陵县| 仁化县| 新泰市| 瓮安县| 定结县|