Php issues related to extracting strings from csv files and solutions

Source: Internet
Author: User
Php issues with extracting strings from csv files and solutions: Use the fgetcsv () function to extract csv & #26684; format data. Secret & #26684; type file, the content in the file is separated by & quot;, & quot. The first line indicates the problem and solution of extracting strings from csv files by php.

The fgetcsv () function is required for php Data in csv format.

Use the following statement

$hd=fopen('test.csv','r');$buf=fgetcsv($hd,1000,',');
Open a file in test.csv format. separate the content with.

The first line indicates the automatic meaning, such as id, messaget, and time.

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

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


It is reasonable to say that from the second line, the output result of this statement should be yes, but you will find no output after trying.

Why?


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

The comparison results are not equal.

God, how can this problem occur? The value obtained from the second line $ buf [1] is "message". how can the length be different?

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


How can this problem be solved?

First use php character encoding detection function mb_detect_encoding ($ buf [1], 'utf-8, EUC-CN, asci '),

If the obtained encoding format is "EUC-CN", then the following statement converts it to utf8 encoding format,

Use the php 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", then we can find that they are finally equal.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.