PHP输出非HTML格式文件总结

在PHP系统开发中,除了显示HTML外,偶尔也会遇到输出文件的问题,关于输出文件,主要是三类,1. 输出磁盘中已有文件 2. 输出生成的文件(如:csv pdf等) 3. 获取生成文件内容,做处理后输出,现在我一一对三类输出做一下总结。

   1. 输出磁盘中已有文件

   这个功能十分常用,一般系统都支持下载上传的文件,这个功能的实现十分简单,可以使用readfile函数轻易完成。

 

Php代码   收藏代码
  1. <?php  
  2. $file = 'a.pdf';  
  3.   
  4. if (file_exists($file)) {  
  5.     header('Content-Description: File Transfer');  
  6.     header('Content-Type: application/octet-stream');  
  7.     header('Content-Disposition: attachment; filename='.basename($file));  
  8.     header('Content-Transfer-Encoding: binary');  
  9.     header('Expires: 0');  
  10.     header('Cache-Control: must-revalidate, post-check=0, pre-check=0');  
  11.     header('Pragma: public');  
  12.     ob_clean();  
  13.     flush();  
  14.      readfile($file);  
  15.     exit;  
  16. }  
  17. ?>   

  2. 输出生成的文件(如:csv pdf等)

  有时候系统那个会输出生成的文件,主要生成csv,pdf,或者打包多个文件为zip格式下载,对于这部分,有些实现方法是将生成的输出成文件再通过文件方式下载,最后删除生成文件,其实可以通过php://output 直接输出生成文件,下面以csv输出为例。

   

Php代码   收藏代码
  1. <?php     
  2. header('Content-Description: File Transfer');     
  3. header('Content-Type: application/octet-stream');     
  4.  header('Content-Disposition: attachment; filename=a.csv');     
  5.  header('Content-Transfer-Encoding: binary');     
  6. header('Expires: 0');     
  7. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');     
  8.  header('Pragma: public');     
  9. ob_clean();     
  10. flush();     
  11. $rowarr=array(array('1','2','3'),array('1','2','3'));     
  12. $fp=fopen('php://output''w');     
  13. foreach($rowarr as $row){     
  14.      fputcsv($fp$row);     
  15. }     
  16. fclose($fp);     
  17. exit;     
  18.     
  19. ?>    

  3. 获取生成文件内容,做处理后输出

  这个在实际中可能非常的少见了,获取生成文件的内容一般是先生成文件,然后读取,最后删除,其实这个可以使用php://temp来做操作,以下仍以csv举例

Php代码   收藏代码
  1. <?php     
  2. header('Content-Description: File Transfer');     
  3. header('Content-Type: application/octet-stream');     
  4.  header('Content-Disposition: attachment; filename=a.csv');     
  5.  header('Content-Transfer-Encoding: binary');     
  6. header('Expires: 0');     
  7. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');     
  8.  header('Pragma: public');     
  9. ob_clean();     
  10. flush();     
  11. $rowarr=array(array('1','2','中文'),array('1','2','3'));     
  12. $fp=fopen('php://temp''r+');     
  13. foreach($rowarr as $row){     
  14.      fputcsv($fp$row);     
  15. }    
  16. rewind($fp);  
  17. $filecontent=stream_get_contents($fp);  
  18. fclose($fp);    
  19. //处理 $filecontent内容  
  20. $filecontent=iconv('UTF-8','GBK',$filecontent);  
  21. echo $filecontent//输出  
  22. exit;     
  23.     
  24. ?>     

 

  关于PHP输出非HTML格式文件总结就到这里,其实PHP中的input/output streams功能十分的强大,用好了,能够简化编码,提高效率,有空不妨关注学习一下。
来源http://renzhen.iteye.com/blog/1003166

你可能感兴趣的:(PHP输出非HTML格式文件总结)