This is a simple example / tutorial on how to read a CSV file with PHP.
Firstly, you need to understand that a CSV file is basically just a text file that adheres to a specific format. In a CSV file, all values are separated by a comma (hence the meaning behind the acronym: Comma Separated Values), whereas individual rows are separated by a newline character. To summarize: A CSV file is made up of commas and newlines. Newline characters separate the rows and commas separate the values / columns.
An example of a CSV file, which I’ve named example.csv:
The first column is the person’s name, the second column is the person’s home country and the last column represents the person’s age. As you can see, each person is separated by a newline character.
In PHP, there is a function called fgetcsv, which will automatically parse CSV fields from a given resource handle (in this case, it will be the file handle resource of our file).
In the following PHP example, I will read the CSV file in and then loop through each row using a while loop:
If you run the above code, you’ll see that the $row variable is an array containing column data. The first value in the row will always be accessible via the index 0 (and so forth).
If you look at the example data, you’ll see that there are three columns in each row. This means that the function fgetcsv will “parse” those three columns into the $row array inside our while loop. For example, if we want to access the person’s country of origin, we can access it like so:
If I want to format the data of each row into something that makes a little more sense:
In the code snippet above, you can see that each value in the row is accessible via a specific array index.
If you’re still a bit confused and you need to get your head around it, be sure to save the example CSV data into a similarly-named file so that you can play around with it!
0 comments:
Post a Comment