日期:2014-05-17  浏览次数:20664 次

PHP输出非HTML格式文件总结

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

?? 1. 输出磁盘中已有文件

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

?

<?php
$file = 'a.pdf';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    ob_clean();
    flush();
     readfile($file);
    exit;
}
?> 

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

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

???

<?php   
header('Content-Description: File Transfer');   
header('Content-Type: application/octet-stream');   
 header('Content-Disposition: attachment; filename=a.csv');   
 header('Content-Transfer-Encoding: binary');   
header('Expires: 0');   
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');   
 header('Pragma: public');   
ob_clean();   
flush();   
$rowarr=array(array('1','2','3'),array('1','2','3'));   
$fp=fopen('php://output', 'w');   
foreach($rowarr as $row){   
     fputcsv($fp, $row);   
}   
fclose($fp);   
exit;   
  
?>  

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

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

<?php   
header('Content-Description: File Transfer');   
header('Content-Type: application/octet-stream');   
 header('Content-Disposition: attachment; filename=a.csv');   
 header('Content-Transfer-Encoding: binary');   
header('Expires: 0');   
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');   
 header('Pragma: public');   
ob_clean();   
flush();   
$rowarr=array(array('1','2','中文'),array('1','2','3'));   
$fp=fopen('php://temp', 'r+');   
foreach($rowarr as $row){   
     fputcsv($fp, $row);   
}  
rewind($fp);
$filecontent=stream_get_contents($fp);
fclose($fp);  
//处理 $filecontent内容
$filecontent=iconv('UTF-8','GBK',$filecontent);
echo $filecontent; //输出
exit;   
  
?>   

?

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