Reading from and Writing to CSV with PHP

Today, we will look into a practical example of reading from and writing to CSV file.

Writing to CSV

First off, we will see how to write data to CSV file using built-in PHP function fputcsv. The regular syntax of the function we often use is as follows:

$file_handle is a file pointer required to be opened with fopen or fsockopen.

$fields is an array variable considered as a row and each item in the array considered as a column in excel spreadsheet.

$delimiter is optional. When it’s omitted, the default delimiter is comma (,).

Example
In the example above, we have defined a variable $users which is a multi-dimensional array representing each first-depth array as row in excel spreadsheet and the items in these arrays are column values. We then create a file pointer with fopen function with write mode.

Then, we iterate over each inner array element in the $users array and write them to the file as a comma-separated values in each row. We finally close the file pointer with fclose function.

Reading from CSV

Next, we will see how to read data from CSV file using fgetcsv. The regular syntax of the function we often use is as follows:

$file_handle is a file pointer required to be opened with fopen or fsockopen.

$length should be greater than the longest line (in characters) to be found in the CSV file.

$delimiter is optional. When it’s omitted, the default delimiter is comma (,).

Example
fgetcsv reads each row from the CSV file till the last row. Notice that we have used filesize function in the second parameter as a length to avoid specifying some unknown length which could result in truncation and whole data is not read from the file.

Conclusion

So, that’s it for the article. Hope it is helpful! If you want to leave any queries regarding the article, drop them in the comments section. We will be glad to hear from you!