Home  >  Article  >  Backend Development  >  Solution to extracting strings from csv format files in php_PHP tutorial

Solution to extracting strings from csv format files in php_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:27:581000browse

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

Use the following sentence

$hd=fopen('test.csv','r');

 $buf=fgetcsv($hd,1000,',');

Open a file in test.csv format, and the contents in the file are separated by "," signs.

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

Starting from the second line, it represents 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] with the "message".

The result of the comparison turned out to be unequal.

Oh my God, how could this problem occur? Obviously the value taken out of $buf[1] in the second line is "message", 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 conversion result $res with the string "message". You can find that they are finally equal.

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