PHP extract strings in CSV format file problems and Solutions _php Tutorial

Source: Internet
Author: User
PHP uses the Fgetcsv () function for data in CSV format.

Use the following statement

$hd =fopen (' test.csv ', ' R '); $buf =fgetcsv ($HD, 1000, ', ');
Opens a Test.csv formatted file with the contents of the file separated by the "," number.

The first row taken represents an automatic meaning, such as id,messaget,time and so on.

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

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


It is supposed to start with the second line, the output of this statement should be yes, but after the attempt you will find no output.

What is this for?


You can use the strlen () function to compare the lengths of $buf[1] with "messages."

The result of the comparison is not equal.

God, how did this happen? Obviously the second row $buf[1] take out the value is "message" ah, how can length different?

This is related to how your CSV format files are encoded.


How to solve this problem?

First, the function mb_detect_encoding ($buf [1], ' utf-8,euc-cn,assii ') is detected using PHP's character encoding.

If the encoded format is "EUC-CN", then the following statement converts 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 result of the conversion $res with the string "message", and you can see that they are finally equal.


http://www.bkjia.com/PHPjc/765066.html www.bkjia.com true http://www.bkjia.com/PHPjc/765066.html techarticle PHP uses the Fgetcsv () function for CSV-like data. Use the following statement $hd =fopen (' test.csv ', ' R '), $buf =fgetcsv ($HD, 1000, ', '); Opens a Test.csv file with the contents of ...

  • 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.