Solution to the garbled problem of php exporting mysql csv: 1. Open the corresponding php file; 2. Just write the BOM logo in the header of the file, with code such as "fwrite($fp, chr(0xEF)." chr(0xBB) . chr(0xBF));".
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, Dell G3 computer.
How to solve the problem of garbled characters when exporting mysql csv from php?
Exporting csv is prone to garbled characters when opened under Windows. It is necessary to write the BOM identifier in the file header, which has been encapsulated into a function.
/** * @param array $rows * @param array $fields * @param string $filename */ function kg_export_csv($rows, $fields = [], $filename = '') { $filename = $filename ?: kg_uniqid(); header("Content-Type: text/csv"); header("Content-Disposition:filename={$filename}.csv"); $fp = fopen('php://output', 'w'); fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF)); if ($fields) fputcsv($fp, $fields); $index = 0; foreach ($rows as $row) { if ($index == 1000) { $index = 0; ob_flush(); flush(); } $index++; fputcsv($fp, $row); }
The key part is to write the BOM in the file header. Logo
fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to solve the garbled problem when php exports mysql csv. For more information, please follow other related articles on the PHP Chinese website!