Home > Backend Development > PHP Problem > How to solve the garbled problem when php exports mysql csv

How to solve the garbled problem when php exports mysql csv

藏色散人
Release: 2023-03-17 14:00:01
Original
1864 people have browsed it

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));".

How to solve the garbled problem when php exports mysql csv

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);
  }
Copy after login

The key part is to write the BOM in the file header. Logo

fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template