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

首頁 > 開發 > PHP > 正文

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

2024-05-04 23:33:42
字體:
來源:轉載
供稿:網友

這篇文章主要介紹了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. echo $separator . $field
  55. $separator = ','
  56. echo "/r/n"
  57. ?> 

希望本文所述對大家的php程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 麻江县| 南汇区| 肥西县| 原阳县| 山东| 吉安县| 临桂县| 杂多县| 固阳县| 应城市| 莒南县| 滦南县| 乐平市| 额济纳旗| 万源市| 凯里市| 马公市| 离岛区| 托克逊县| 焦作市| 襄樊市| 西城区| 涪陵区| 塘沽区| 商城县| 隆德县| 博兴县| 澄江县| 大理市| 沿河| 盐山县| 保定市| 渝中区| 凯里市| 永寿县| 张家口市| 洮南市| 江油市| 麦盖提县| 阿克陶县| 曲靖市|