A solution to the occurrence of a string in a CSV format file extracted from PHP

Source: Internet
Author: User

PHP data with CSV format uses the Fgetcsv () function.

Use the following statement

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

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

Open a file in test.csv format, with the contents of the file separated by the "," number.

The first line taken out represents the automatic meaning, such as id,messaget,time and so on.

Start at the second line and represent specific data, such as 1, message, 12:00.

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

Logically, from the second line, the output of this statement should be yes, but after you try you will find no output.

What is this for?

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

The result of comparison is not equal.

Oh, my God, how did this happen? Clearly the second line of $buf[1] The value is "message" Ah, how can the length of different?

This is related to the way your CSV format file is encoded.

How to solve this problem?

First use PHP's character code to detect the function mb_detect_encoding ($buf [1], ' utf-8,euc-cn,assii '),

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

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

Comparing the result of the transformation to the string "message", it can be found that they are finally equal $res.

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.