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] => ))