Home Backend Development PHP Tutorial PHP generates CSV files and opens garbled characters in Excel_PHP tutorial

PHP generates CSV files and opens garbled characters in Excel_PHP tutorial

Jul 13, 2016 am 10:43 AM
csv excel php one Why Garbled characters classmate Open document have generate use question

Today a classmate asked me why garbled characters appear when the CSV file generated by PHP is opened in Excel. Below, the editor will find some common methods for you. I hope this method will be helpful to all my friends.

Baidu found out after verification

The UTF-8 encoded CSV file generated by PHP displays garbled characters in Chinese when opened in Excel. This is because there is no BOM in the output CSV file.

We just need to deal with it briefly

So how to output BOM in PHP?

Before all content is output

The code is as follows
 代码如下 复制代码

print(chr(0xEF).chr(0xBB).chr(0xBF));

Copy code


print(chr(0xEF).chr(0xBB).chr(0xBF));
 代码如下 复制代码

$now = gmdate("D, d M Y H:i:s");
header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
header("Last-Modified: {$now} GMT");

// force download
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");

// disposition / encoding on response body
header("Content-Disposition: attachment;filename={$filename}");
header("Content-Transfer-Encoding: binary");
$items_data=array(
'0'=>array('title'=>'test test test1'),
'1'=>array('title'=>'test test test2'),
'2'=>array('title'=>'test test test3')
)
print(chr(0xEF).chr(0xBB).chr(0xBF));//设置utf-8 + bom ,处理汉字显示的乱码
echo array2csv($items_data);
 
function array2csv(array &$array)
{
   if (count($array) == 0) {
     return null;
   }
   ob_start();
   $df = fopen("php://output", 'w');
   fputcsv($df, array_keys(reset($array)));
   foreach ($array as $row) {
      fputcsv($df, $row);
   }
   fclose($df);
   return ob_get_clean();
}
?>

Example. When php generates csv, we can do this

) print(chr(0xEF).chr(0xBB).chr(0xBF));//Set utf-8 + bom to deal with garbled characters displayed in Chinese characters
The code is as follows

Copy code

$now = gmdate("D, d M Y H:i:s"); header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");

header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");

header("Last-Modified: {$now} GMT");

// force download

header("Content-Type: application/force-download");

header("Content-Type: application/octet-stream"); ​​

header("Content-Type: application/download");

// disposition / encoding on response body

header("Content-Disposition: attachment;filename={$filename}"); header("Content-Transfer-Encoding: binary"); $items_data=array( '0'=>array('title'=>'test test test1'), '1'=>array('title'=>'test test test2'),

'2'=>array('title'=>'test test test3')
echo array2csv($items_data);

function array2csv(array &$array)

{ Return null; } ob_start(); $df = fopen("php://output", 'w'); fputcsv($df, array_keys(reset($array))); foreach ($array as $row) {          fputcsv($df, $row); } fclose($df); Return ob_get_clean(); }
?>
Another way is to use Office Open Microsoft Office 2010 Excel, data-self-text, as shown in the figure: Import this csv format file, and you are also required to select encoding, as shown in the figure: Select UTF-8 here. After opening it, you will find that the garbled characters are eliminated, as shown in the picture: Supplement: UTF-8 is the most widely used implementation of unicode encoding on the Internet. One of the biggest features of UTF-8 is that it is a variable-length encoding method. It can use 1~4 bytes to represent a symbol, and the byte length varies according to different symbols http://www.bkjia.com/PHPjc/633200.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/633200.htmlTechArticleToday a classmate asked me why the CSV file generated by PHP would appear garbled when opened in Excel. The editor will tell you below I found some common methods, I hope this method will be helpful to all my friends...
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Coinbase Exchange Login Port 2025 Coinbase Exchange Login Port 2025 Mar 21, 2025 pm 05:51 PM

Coinbase Security Login Guide: How to Avoid Phishing Sites and Scams? Phishing and scams are becoming increasingly rampant, and it is crucial to securely access the Coinbase official login portal. This article provides practical guides to help users securely find and use the latest official login portal of Coinbase to protect the security of digital assets. We will cover how to identify phishing sites, and how to log in securely through official websites, mobile apps or trusted third-party platforms, and provide suggestions for enhancing account security, such as using a strong password and enabling two-factor verification. To avoid asset losses due to incorrect login, be sure to read this article carefully!

Ouyi Exchange web version registration portal Ouyi registration portal Ouyi Exchange web version registration portal Ouyi registration portal Mar 20, 2025 pm 05:48 PM

This article details how to register an account on the official website of Ouyi OKX Exchange and start cryptocurrency trading. As the world's leading cryptocurrency exchange, Ouyi provides a wide range of trading varieties, multiple trading methods and strong security guarantees, and supports convenient withdrawal of a variety of fiat and cryptocurrencies. The article covers the search methods for Ouyi official website registration entrance, detailed registration steps (including email/mobile registration, information filling, verification code verification, etc.), as well as precautions after registration (KYC certification, security settings, etc.), and answers common questions to help novice users quickly and safely complete Ouyi account registration and start a cryptocurrency investment journey.

Ouyi okx official entrance address Ouyi official link Ouyi okx official entrance address Ouyi official link Mar 21, 2025 pm 06:09 PM

In digital currency transactions, security is crucial. Due to the prevalence of phishing, it is crucial to find Ouyi OKX official entrance address and official links. Incorrect links can lead to account theft, asset loss and identity theft. This article will provide a comprehensive guide to secure access to the Ouyi OKX official platform, helping users identify and avoid phishing websites and protecting the security of digital assets. We will introduce how to confirm the official portal of Ouyi OKX through official websites, official applications, official social media accounts and other trusted channels, and provide important security tips, such as avoiding unknown links, using strong passwords and enabling two-factor verification, to ensure your transactions are safe and reliable.

Ouyi official address Ouyi okx official entrance address Ouyi official address Ouyi okx official entrance address Mar 21, 2025 pm 06:12 PM

With the increasing popularity of digital currency trading, it is crucial to choose a safe and reliable trading platform. As the world's leading digital asset exchange, OKX's security has attracted much attention. However, many phishing websites impersonate OKX official, causing users to face the risks of account security and asset losses. This article will explain in detail how to identify and access the real Ouyi OKX official website and APP entrance to avoid phishing website traps and ensure the security of your digital assets. Through various channels such as official website verification, official app download, official social media channels, and official customer service consultation, you can effectively identify and access the OKX official platform to ensure the security of your transactions. Please be sure to carefully check the domain name, check the HTTPS protocol, and improve network security awareness.

BitMEX Exchange's latest official website entrance BitMEX Exchange's latest official website entrance Mar 21, 2025 pm 06:03 PM

As a veteran cryptocurrency derivatives trading platform, the accuracy of its official website entrance is crucial. Due to rampant phishing websites, misent entry into fake websites can lead to account theft and loss of funds. This article aims to guide users to safely access the BitMEX official website, provide various methods such as trusted cryptocurrency information platforms (such as CoinMarketCap, CoinGecko), official social media, verification of existing addresses and official support channels, and emphasizes the use of security measures such as two-factor verification, regular password changes and use of security software to help users effectively avoid risks and ensure account security.

Simulation trading software for currency speculation Simulation trading software for currency speculation Mar 19, 2025 pm 04:24 PM

Simulated transactions, also known as simulated disks or virtual transactions, are an excellent way to learn and practice cryptocurrency trading, allowing users to trade with virtual funds without taking any actual financial risks. By simulated trading, you can learn trading platform operations at zero risk, test trading strategies, practice emotional control, and become familiar with leverage use. Exchanges such as Binance, Ouyi, and Sesame Open Door all provide simulated trading platforms, and software such as TradingView and MetaTrader also provide similar functions. Although simulated trading can effectively improve trading skills, you should pay attention to the differences between them and real trading, and be cautious and do not overconfidence. This article will introduce the advantages, usage methods and precautions of simulated transactions in detail to help you stabilize the cryptocurrency market.

How to download gate exchange Download gate official app How to download gate exchange Download gate official app Mar 20, 2025 pm 05:57 PM

Gate.io Sesame Open Exchange App Download Guide: This article explains the official Gate.io Exchange App Download Method to help you trade cryptocurrency anytime, anywhere. Gate.io App has the advantages of convenience, good user experience, comprehensive functions (spot, contract, leverage, financial management, etc.) and strong security, and provides real-time market information. To ensure safety, be sure to download the App from the official website of Gate.io to avoid downloading malware. The article introduces the official website download steps and iOS and Android installation procedures in detail, and provides frequently asked questions and security suggestions to help you quickly get started with the Gate.io App and start a safe and convenient cryptocurrency trading journey.

Binance Exchange web version registration portal Binance Exchange web version registration portal Mar 20, 2025 pm 05:42 PM

This article aims to guide users to register the Binance Exchange web version safely and start their journey of digital assets. As the world's leading cryptocurrency exchange, Binance has a huge user base and a rich trading variety. Its advantages include: world's leading trading volume, rich currency selection, diversified trading products, strong security, convenient withdrawal experience, and an active community and a complete ecosystem. The article will introduce in detail the steps to register Binance through official channels, and emphasize the importance of security measures such as completing identity authentication (KYC), enabling two-factor verification (2FA), and setting a fund password after registration, reminding users to be wary of phishing websites and fraudulent information, and invest rationally.

See all articles