首页 > 开发 > 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', $conn) or 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, $conn) or 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. /* 
  37. * output data rows (if atleast one row exists) 
  38. */ 
  39. while ($row) { 
  40. echocsv($row); 
  41. $row = mysql_fetch_assoc($result); 
  42. } 
  43.  
  44. /* 
  45. * echo the input array as csv data maintaining consistency with most CSV implementations 
  46. * - uses double-quotes as enclosure when necessary 
  47. * - uses double double-quotes to escape double-quotes 
  48. * - uses CRLF as a line separator 
  49. */ 
  50.  
  51. function echocsv($fields) 
  52. { 
  53. $separator = ''; 
  54. foreach ($fields as $field) { 
  55. if (preg_match('///r|//n|,|"/', $field)) { 
  56. $field = '"' . str_replace('"', '""', $field) . '"'; 
  57. } 
  58. echo $separator . $field; 
  59. $separator = ','; 
  60. } 
  61. echo "/r/n"; 
  62. } 
  63. ?> 

希望本文所述对大家的php程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表