Home >Backend Development >PHP Tutorial >Problems and solutions when extracting strings from csv format files in PHP_PHP Tutorial

Problems and solutions when extracting strings from csv format files in PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 10:30:33940browse

PHP needs to use the fgetcsv() function for data in csv format.

Use the following sentences

$hd=fopen('test.csv','r');
$buf=fgetcsv($hd,1000,',');
Open a file in test.csv format. The content in the file is separated by ",".

The first line taken out represents automatic meaning, such as id, message, time, etc.

Start from the second line to indicate specific data, such as 1, message, 12:00.

if($buf[1]=="some messages") echo "yes";


It stands to reason that starting from the second line, the output result of this statement should be yes, but after trying it, you will find that there is no output.

Why is this?


You can use the strlen() function to compare the length of $buf[1] and the "message".

The result of the comparison turned out to be unequal.

Oh my god, how could such a problem happen? Obviously the value extracted from $buf[1] in the second line is "message", so why are the lengths different?

This is related to the encoding method of your csv format file.


How to solve this problem?

First use PHP's character encoding detection function mb_detect_encoding($buf[1],'UTF-8,EUC-CN,ASSII'),

If the extracted encoding format is "EUC-CN", then use the following statement to convert it to the utf8 encoding format,

Use PHP's character conversion function mb_convert_encoding(), $res=mb_convert_encoding($buf[1],'UTF-8','EUC-CN').

Compare the converted result $res with the string "message". You can find that they are finally equal.


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/765066.htmlTechArticlePHP with csv-style data needs to use the fgetcsv() function. Use the following statement $hd=fopen('test.csv','r');$buf=fgetcsv($hd,1000,','); to open a test.csv file. The content in the file starts with ...
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