-
- $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');
- b_clean();
- flush();
- readfile($file);
- exit;
- }
- ?>
Copy code
2. Output the generated file (such as: csv pdf, etc.)
Sometimes the system will output the generated files, mainly generating csv, pdf, or packaging multiple files for download in zip format. For this part, some implementation methods are to output the generated files into files and then download them through files, and finally delete them. To generate a file, you can actually directly output the generated file through php://output. The following uses csv output as an example.
-
- 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;
- ?>
Copy code
3. Get the content of the generated file, process it and output it
To obtain the content of a generated file, you usually generate the file first, then read it, and finally delete it. In fact, you can use php://temp to do this. The following is still using csv as an example.
-
- 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','Chinese'),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);
- //Process $filecontent content
- $filecontent=iconv('UTF-8','GBK ',$filecontent);
- echo $filecontent; //Output
- exit;
- ?>
Copy code
The input/output streams function in php is very powerful. If used well, it can simplify coding and improve Efficiency, I suggest you focus on it.
|