sql - Set character coding when generating xls file with php

How can I set UTF8 character coding with this code?

My problem is that when I open the exported file in Excel, I have to set the encoding manually.

$filename = "termekek.xls";

        header("Content-Disposition: attachment; filename=\"$filename\"");
        header("Content-Type: application/vnd.ms-excel");

        $flag = false;
        $result = mysqli_query($kapcs, $sql) or die('SQL error - '.mysqli_error($kapcs));
        while($row = mysqli_fetch_assoc($result)) 
        {
            if(!$flag) 
            {
                echo implode("\t", array_keys($row)) . "\r\n";
                $flag = true;
            }
            array_walk($row, __NAMESPACE__ . '\cleanData');
            echo implode("\t", array_values($row)) . "\r\n";
        }
        exit;

1 Answer

  1. Randy- Reply

    2019-11-14

    You need to send a UTF8 BOM (Byte Order Mark) after sending your headers and before the data:

    $filename = "termekek.xls";
    
    header("Content-Disposition: attachment; filename=\"$filename\"");
    header("Content-Type: application/vnd.ms-excel");
    echo "\xEF\xBB\xBF"; // UTF8 BOM
    
    $flag = false;
    $result = mysqli_query($kapcs, $sql) or die('SQL error - '.mysqli_error($kapcs));
    
    while ($row = mysqli_fetch_assoc($result)) {
        if (!$flag) {
            echo implode("\t", array_keys($row)) . "\r\n";
            $flag = true;
        }
        array_walk($row, __NAMESPACE__ . '\cleanData');
        echo implode("\t", array_values($row)) . "\r\n";
    }
    
    exit();
    

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>