What are the best practices for handling character encoding in PHP when displaying data from Excel files on a website?

When displaying data from Excel files on a website using PHP, it's important to handle character encoding properly to avoid displaying garbled text. One way to do this is by using the mb_convert_encoding function to convert the data to the desired character encoding before displaying it on the website.

// Read Excel file and convert data to UTF-8 encoding
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$spreadsheet = $reader->load('example.xlsx');
$worksheet = $spreadsheet->getActiveSheet();

foreach ($worksheet->getRowIterator() as $row) {
    $cellIterator = $row->getCellIterator();
    $cellIterator->setIterateOnlyExistingCells(FALSE); // Loop through all cells, even if they are empty
    foreach ($cellIterator as $cell) {
        $cellValue = $cell->getValue();
        $cellValue = mb_convert_encoding($cellValue, 'UTF-8', 'auto');
        echo $cellValue . '<br>';
    }
}