PHP CSV

Summary: in this tutorial, you will learn how to deal with CSV files in PHP including creating and reading CSV files.

CSV stands for comma-separated values. A CSV file is a text file that stores tabular data in form of comma-separated values. A CSV file stores each record per line. It may have a header.

The following illustrates the content of a sample CSV file:

php csv file example

When you view the CSV file in a text editor, it looks like the following screenshot:

php csv file text format

The comma (,) is often used to separate fields in a CSV file. In case the field value contains a comma(,), it is placed inside double quotes e.g., “Facebook, Inc.” . Not only the comma (,) but also other character e.g., semicolon (;)  could be used to separated fields.

Even the CSV file is a plain text file, its extension is csv, not txt.

PHP provides some useful functions that allow you to create and read CSV file.

PHP create CSV files

To format a line as CSV and write it to a file pointer, you use the fputcsv() function. The following example creates a CSV file named stock.csv:

How it works.

  • First, we defined an array that holds stock data.
  • Second, we opened the stock.csv file for writing using the fopen() function.
  • Third, we looped through the stock data array and formated each element as a CSV.
  • Finally, we closed the file using the fclose() function.

PHP read CSV files

To read CSV files, you use the fgetcsv() functions. The fgetcsv() function reads a line of CSV data from the file pointer’s position and places it into an array. Each field in the CSV record is placed in the array as an element. Once you have data in the array, it is easier to  manipulate.

The function fgetcsv() returns false if there was an error occurred while reading the file or the file pointer reached the end-of-file.

The following example shows you how to read the stock.csv file that we have created before.

How the script works.

  • First, we opened the stock.csv file for reading using the fopen() function.
  • Second, we read each line in the file through the $fh file handle and placed it into an array. We used the while loop to read the entire CSV file until the file pointer reached the end-of-file.
  • Third, we closed the file and displayed the array.

In this tutorial, you have learned how to create CSV files using the fputcsv() function and read the CSV file using the fgetcsv() function.

  • Was this tutorial helpful ?
  • YesNo