Home  >  Article  >  Backend Development  >  Simple example of php exporting CSV file

Simple example of php exporting CSV file

WBOY
WBOYOriginal
2016-07-25 08:55:03970browse
  1. /**

  2. * Export csv file, header function example
  3. * edit: bbs.it-home.org
  4. */
  5. header( "Cache-Control: public" );
  6. header( "Pragma: public" );
  7. header("Content-type:application/vnd.ms-excel");
  8. header("Content-Disposition:attachment;filename=txxx.csv");
  9. header('Content-Type:APPLICATION/OCTET-STREAM');

  10. ob_start();

  11. $header_str = iconv("utf-8",'gbk',"信息id,标题,名称,电话,QQ,Email,内容,时间n");
  12. $file_str="";
  13. $mysqli= new mysqli('localhost','root','','test');

  14. if (mysqli_connect_errno()) {

  15. printf("Connect failed: %sn", mysqli_connect_error());
  16. exit();
  17. }
  18. $sql='select * from messages';
  19. $mysqli->query("set names utf8 ;");
  20. $result=$mysqli->query($sql);

  21. if($result){

  22. while ($row = mysqli_fetch_assoc($result)){
  23. $file_str.= $row['id'].','.$row['title'].','.$row['name'].','."'{$row['telephone']}'".','.$row['qq'].','.$row['email'].','.str_ireplace(',',',',$row['content']).','.$row['retime']."n";
  24. }
  25. }else{
  26. echo "nonono!!!";
  27. }
  28. $file_str= iconv("utf-8",'gbk',$file_str);
  29. ob_end_clean();
  30. echo $header_str;
  31. echo $file_str;
  32. ?>

复制代码


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn