Read file does not enter the accents

-1
if(isset($_GET['rf'])){

  $filename=$_GET['rf'];
  //$path=$_SERVER['DOCUMENT_ROOT'].'/'.$filename;
  //echo $path;
  if(file_exists("subs/" . $filename)){

       header('Content-Type: text/plain');
       //header('Content-Disposition: attachment; filename='.$filename);  <-- DOWNLOAD FILE
       header('Content-Length: ' . filesize("subs/" . $filename));
       header('Expires: 0');
       header('Cache-Control: must-revalidate');
       header('Pragma: public');

       ob_clean();
       flush();
       readfile(utf8_encode("subs/" . $filename));
  }
}
  • Appears without accents when reading the file


    
asked by anonymous 05.11.2017 / 16:45

1 answer

1

The problem is not only the utf-8 charset that is not being set in the headers of php. The content read by the readfile() function is not being converted to utf-8. For this to happen some changes must be made:

  • remove the flush command (prevent readfile() from being automatically printed)
  • add ob_start() to store contents of readfile()
  • Finally get the contents of readfile() with ob_get_clean () and make the encode for utf-8

Putting it all together:

...

header('Content-Type: text/plain');
//header('Content-Disposition: attachment; filename='.$filename);  <-- DOWNLOAD FILE
header('Content-Length: ' . filesize($filename) . ";charset=UTF-8");
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');

ob_clean();
//armazena o que for impresso por readfile
ob_start();

readfile(utf8_encode($filename));

//obtem o que foi impresso por readfile e faz o encode
echo utf8_encode(ob_get_clean());

...
    
06.11.2017 / 03:32