Home >Backend Development >PHP Tutorial >Problems and solutions when extracting strings from csv format files in PHP_PHP Tutorial
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";
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.