PHP Export CSV ให้รองรับข้อมูลภาษาไทย

PHP Knowledge เป็น บอร์ดรวามความรู้ php เน้นบทความ แนวทางการเขียนโปรแกรม บันทึกกันลืม เพื่อให้สมาชิกได้เขียนความรู้ที่ตัวเองมีให้สมาชิกท่านอื่นๆ ได้ เข้ามาอ่าน และ ไว้อ่านเองกันลืมด้วย

Moderator: mindphp, ผู้ดูแลกระดาน

ภาพประจำตัวสมาชิก
thatsawan
PHP VIP Members
PHP VIP Members
โพสต์: 28508
ลงทะเบียนเมื่อ: 31/03/2014 10:02 am
ติดต่อ:

PHP Export CSV ให้รองรับข้อมูลภาษาไทย

โพสต์ที่ยังไม่ได้อ่าน โดย thatsawan »

โค้ด: เลือกทั้งหมด

  $csv_data = array(
                    array('id', 'ชื่อผู้ใช้งาน', 'ทดสอบ'),
                    array('1', 'ชื่อผู้ใช้งาน', 'ทดสอบ'),
                 
                );
                $this->export_data_to_csv($csv_data, $filename); 

โค้ด: เลือกทั้งหมด

 /**
     *
     * Exports an associative array into a CSV file using PHP.
     *
     * @see https://stackoverflow.com/questions/21988581/write-utf-8-characters-to-file-with-fputcsv-in-php
     *
     * @param array     $data       The table you want to export in CSV
     * @param string    $filename   The name of the file you want to export
     * @param string    $delimiter  The CSV delimiter you wish to use. The default ";" is used for a compatibility with microsoft excel
     * @param string    $enclosure  The type of enclosure used in the CSV file, by default it will be a quote "
     */
    function export_data_to_csv($data, $filename = 'export', $delimiter = ';', $enclosure = '"') {
        // Tells to the browser that a file is returned, with its name : $filename.csv
        header("Content-disposition: attachment; filename=$filename.csv");
        // Tells to the browser that the content is a csv file
        header("Content-Type: text/csv");

        // I open PHP memory as a file
        $fp = fopen("php://output", 'w');

        // Insert the UTF-8 BOM in the file
        fputs($fp, $bom = ( chr(0xEF) . chr(0xBB) . chr(0xBF) ));

        // I add the array keys as CSV headers
        fputcsv($fp, array_keys($data[0]), $delimiter, $enclosure);

        // Add all the data in the file
        foreach ($data as $fields) {
            fputcsv($fp, $fields, $delimiter, $enclosure);
        }

        // Close the file
        fclose($fp);

        // Stop the script
        die();
    }
 
อ้างอิงจาก
https://bastienmalahieude.fr/en/export- ... oft-excel/

ผลที่ได้
2019-09-30_13-39-37.jpg
2019-09-30_13-39-37.jpg (11.17 KiB) Viewed 3157 times

ผู้ใช้งานขณะนี้

สมาชิกกำลังดูบอร์ดนี้: ไม่มีสมาชิกใหม่ และบุคลทั่วไป 79