query($sql);if($result){while ($row = mysqli_fetch_assoc($result)){ $file_">
当前位置:Gxlcms > PHP教程 > php导出CSV文件的简单示例

php导出CSV文件的简单示例

时间:2021-07-01 10:21:17 帮助过:31人阅读

  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. ?>

人气教程排行