Home > Article > Backend Development > What should I do if the php download file is garbled?
Solution to garbled code when downloading files in php: First use the ob_clean() function to discard the contents of the output buffer; then use the ob_flush() function to flush out the contents of the output buffer; and finally download the file.
Function introduction:
The ob_clean() function is used to discard the contents of the output buffer.
ob_flush() flushes out (sends out) the contents of the output buffer.
(Related video recommendations: java video tutorial)
Solution:
Before downloading the file, use the above two functions for processing. Then download it again, so that there will be no garbled characters.
Code implementation:
<?php /** * 强制下载文件 * @param string $filename 变量 * @param string $name 变量 * @return mixed */ function download($filename,$name){ if ((isset($filename))&&(file_exists($filename))){ header("Content-length: ".filesize($filename)); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . $name . '"'); ob_clean(); flush(); readfile("$filename"); } else { $info="Looks like file does not exist!"; return $info; } } ?>
Related recommendations: php training
The above is the detailed content of What should I do if the php download file is garbled?. For more information, please follow other related articles on the PHP Chinese website!