What steps can be taken to ensure that text files with different character encodings are displayed correctly on a webpage using PHP?

When displaying text files with different character encodings on a webpage using PHP, it is important to properly handle the encoding of the text to ensure it is displayed correctly. One way to do this is by detecting the encoding of the text file and converting it to UTF-8 before displaying it on the webpage.

// Read the contents of the text file
$file_contents = file_get_contents('text_file.txt');

// Detect the encoding of the text file
$encoding = mb_detect_encoding($file_contents, 'UTF-8, ISO-8859-1', true);

// Convert the text file contents to UTF-8
if ($encoding != 'UTF-8') {
    $file_contents = mb_convert_encoding($file_contents, 'UTF-8', $encoding);
}

// Output the text file contents on the webpage
echo $file_contents;