Skip to content
PHP Logo

What are the best practices for handling character encoding in PHP headers for file output?

When outputting files in PHP, it is important to set the correct character encoding in the headers to ensure that the file is displayed or downloaded correctly. This can be done by setting the "Content-Type" header to specify the encoding type, such as UTF-8. Additionally, it is important to use functions like "mb_convert_encoding" to convert the file content to the desired encoding before outputting it.

php
<?php
// Set the content type and encoding for the file
header('Content-Type: text/plain; charset=UTF-8');

// Convert the file content to UTF-8 encoding
$file_content = file_get_contents('example.txt');
$file_content = mb_convert_encoding($file_content, 'UTF-8');

// Output the file content
echo $file_content;