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

How to solve the garbled problem when php exports mysql csv

藏色散人
藏色散人Original
2022-11-19 09:49:101812browse

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);
  }

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!

Statement:
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