php输出非html格式文件的总结

WBOY
풀어 주다: 2016-07-25 09:05:31
원래의
1231명이 탐색했습니다.
  1. $file = 'a.pdf';
  2. if (file_exists($file)) {
  3. header('Content-Description: File Transfer');
  4. header('Content-Type: application/octet-stream');
  5. header('Content-Disposition: attachment; filename='.basename($file));
  6. header('Content-Transfer-Encoding: binary');
  7. header('Expires: 0');
  8. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  9. header('Pragma: public');
  10. b_clean();
  11. flush();
  12. readfile($file);
  13. exit;
  14. }
  15. ?>
复制代码

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

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

3. 获取生成文件内容,做处理后输出 获取生成文件的内容一般是先生成文件,然后读取,最后删除,其实这个可以使用php://temp来做操作,以下仍以csv举例

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

php中的input/output streams功能十分的强大,用好了,能够简化编码,提高效率,建议大家专入一下哦。



원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!