The first element in a while? Loop

I am writing a PHP script that imports csv and inserts into a table, but I need to get the first row so that I have the field names ... somewhere my csv

id artist song 11 NewBee great stuff 10 anotherNewbee even better 6 NewArtist New song 

As you can see, the first line is the name of the fields that I need. here is my loop

 $handle = fopen('csvs/'.$_FILES["csv"]["name"], 'r'); while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) { print_r($data); //do something with it but i need the first time around array(3) { [0]=> string(2) "id" [1]=> string(6) "artist" [2]=> string(4) "song" } array(3) { [0]=> string(2) "11" [1]=> string(6) "NewBee" [2]=> string(1) "great stuff" } array(3) { [0]=> string(2) "10" [1]=> string(13) "anotherNewbee" [2]=> string(1) "even better"} 

How to get the first one and put them in variables and continue the data cycle using these fields in the insert statement

+4
source share
3 answers

Will this work for you?

 $row = 1; while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) { if($row == 1) { // do something } else { // do something } ++$row; } 
+12
source

Before your while block, just run the fgetcsv function at a time and save the field headers.

+3
source

Deep or matte mod methods will work fine. Here mattmoon9 answer will look like structured in code (also based on my comment on the answer):

 $handle = fopen('csvs/'.$_FILES["csv"]["name"], 'r'); if (($columns = fgetcsv($handle, 1000, ',')) !== false) { while (($data = fgetcsv($handle, 1000, ',')) !== false) { // Process data } // Insert into database using $columns as table column names } else { // The file couldn't be parsed as CSV } 
+2
source

All Articles