PHP reads CSV file content

Source: Internet
Author: User

PHP has a way to directly read the contents of the CSV file, that is, fgetcsv (). For detailed parameters and instructions, refer to the PHP manual.

It may be a bit of fun tonight, or how to use this function to write a function to read the contents of the CSV file, which can correspond to the field name in the table. The first row in the table stores data as the field name. The second row begins with your personal data. You can read the data in this way and insert the corresponding fields in the data table.

CSV file:

Field 1 Field 2 Field 3 Field 4
Value 1_1 Value 1_2 Value: 1_3 Value: 1_4
Value 2_1 2_2 Value 2_3 Value 2_4

 

PHP code:

<? Phpfunction getcsvdata ($ filename) {$ ROW = 1; // The first line starts if ($ handle = fopen ($ filename, "R "))! = False) {While ($ datasrc = fgetcsv ($ handle ))! = False) {$ num = count ($ datasrc); For ($ C = 0; $ C <$ num; $ C ++) // column {if ($ ROW = 1) // The first row serves as the field {$ dataname [] = $ datasrc [$ C]; // field name} else {foreach ($ dataname as $ k => $ v) {if ($ k = $ C) // corresponding field {$ data [$ v] = $ datasrc [$ C] ;}}} if (! Empty ($ data) {$ datartn [] = $ data; unset ($ data) ;}$ row ++ ;}fclose ($ handle); return $ datartn ;}} $ aData = getcsvdata('test.csv '); print_r ($ aData);?>

Test results:

Array(    [0] => Array        (            [a] => test3            [b] => test4            [c] =>         )    [1] => Array        (            [a] => test5            [b] =>             [c] =>         )) 

 

 

 

 

 



     
   
 

 

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.