Home  >  Article  >  Backend Development  >  What should I do if the php download file is garbled?

What should I do if the php download file is garbled?

王林
王林Original
2020-11-04 13:48:532003browse

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.

What should I do if the php download file is garbled?

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(&#39;Content-Type: application/octet-stream&#39;);
     header(&#39;Content-Disposition: attachment; filename="&#39; . $name . &#39;"&#39;);
     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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn