Read file does not insert accents

Asked

Viewed 90 times

-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


inserir a descrição da imagem aqui

  • It seems to me that I have yet to define the chatset in the header that defines the Content-Type. Which means it may not be visualized as utf-8 though it has been read as utf-8

  • I recommend reading: https://answall.com/questions/29455/comorconverter-caracteres-em-utf-8-no-php/29470#29470

1 answer

1


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

  • remove the command flush (prevent the content of readfile() be printed automatically)
  • add ob_start() to store the contents of readfile()
  • Finally obtain the content of readfile() with ob_get_clean() and do the Encode for utf-8

Put 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());

...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.