PHP CSV
A quick introduction to CSV files
CSV stands for comma-separated values. A CSV file is a text file that stores tabular data in the form of comma-separated values. A CSV file stores each record per line. And it may have a header.
When you open a CSV file using a spreadsheet application, you’ll see that the file is nicely formatted like this:
However, if you view the CSV file in a text editor, it looks like the following:
Symbol,Company,Price
GOOG,"Google Inc.",800
AAPL,"Apple Inc.",500
AMZN,"Amazon.com Inc.",250
YHOO,"Yahoo! Inc.",250
FB,"Facebook, Inc.",30
Code language: plaintext (plaintext)
Typically, a CSV file uses a comma (,
) to separate fields in a CSV file. If the field content also contains a comma(,
), the CSV file surrounds that field with double quotes, e.g., “Facebook, Inc..”
Besides using the comma (,
) character, a CSV file may use other characters to separate fields such as semicolon (;
).
Writing to a CSV file
To write a line to a CSV file, you use the fputcsv()
function:
fputcsv ( resource $handle , array $fields , string $delimiter = "," , string $enclosure = '"' , string $escape_char = "\\" ) : int|false
Code language: PHP (php)
The following example uses the fputcsv()
function to write data to a CSV file:
$data = [
['Symbol', 'Company', 'Price'],
['GOOG', 'Google Inc.', '800'],
['AAPL', 'Apple Inc.', '500'],
['AMZN', 'Amazon.com Inc.', '250'],
['YHOO', 'Yahoo! Inc.', '250'],
['FB', 'Facebook, Inc.', '30'],
];
$filename = 'stock.csv';
// open csv file for writing
$f = fopen($filename, 'w');
if ($f === false) {
die('Error opening the file ' . $filename);
}
// write each row at a time to a file
foreach ($data as $row) {
fputcsv($f, $row);
}
// close the file
fclose($f);
Code language: HTML, XML (xml)
How it works.
- First, define an array that holds the stock data.
- Second, open the
stock.csv
file for writing using thefopen()
function with the'w'
mode. - Third, loop through the
$data
array and write each each element as a line to the CSV file. - Finally, close the file using the
fclose()
function.
Writing Unicode characters
If you’re dealing with Unicode characters especially creating a CSV file for using Microsoft Excel, you need to change the file header using the fputs()
function after opening the file as follows:
$f = fopen($filename, 'w');if ($f === false) {
die('Error opening the file ' . $filename);
}
fputs($f, (chr(0xEF) . chr(0xBB) . chr(0xBF))); // support unicode
// writing to a CSV file
//....
Code language: HTML, XML (xml)
Reading from a CSV file
To read a CSV file, you use the fgetcsv()
function:
fgetcsv ( resource $stream , int $length = 0 , string $separator = "," , string $enclosure = '"' , string $escape = "\\" ) : array
Code language: PHP (php)
The fgetcsv()
function reads a line of CSV data from the file pointer’s position and places it into an array; each line of the CSV file is an array element.
The function fgetcsv()
returns false
if there is an error occurred while reading the file or when the file pointer reaches the end-of-file.
The following example shows how to read the stock.csv
file created above:
$filename = './stock.csv';
$data = [];
// open the file
$f = fopen($filename, 'r');
if ($f === false) {
die('Cannot open the file ' . $filename);
}
// read each line in CSV file at a time
while (($row = fgetcsv($f)) !== false) {
$data[] = $row;
}
// close the file
fclose($f);
Code language: HTML, XML (xml)
How the script works.
- First, open the
stock.csv
file for reading using thefopen()
function. - Second, read each line in the file through the file handle and place it into an array. We use the while loop to read the entire CSV file until the file pointer reached the end-of-file.
- Third, close the file and display the array.
Summary
- Use the
fputcsv()
function to write a row to a CSV file. - Use the
fgetcsv()
function to read a row from a CSV file.