欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php导出CSV文件的简单示例

程序员文章站 2022-03-29 12:26:48
...
  1. /**

  2. * 导出csv文件,header函数示例
  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: %s\n", 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. ?>
复制代码