burger menu icon
WillMaster

WillMaster > LibraryMiscellaneous

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

Handling CSV Files With PHP

As a programmer, you are likely to be tasked with reading and writing CSV files.

CSV (Comma-Separated Values) used to be the most popular format for data files compatible with various types of software. It may still be the most popular. Other popular formats are XML and JSON. This article is dedicated to CSV.

If you are not a programmer, you may want to skip this article.

But if you are a programmer, I'll describe how to read and write CSV files with PHP.

I'll first describe how to write a CSV file. Then, how to read it.

To write data, you have to have data to write. Well, duh. Of course. So we'll make some up. Let's use this array:

<?php
$testing = array( 123, 'abc', 'the "old" tire', "Sadine's nice, spacious elf house" );
?>

A line of comma-separated values is simply that; the values on the line are separated with a comma.

If the value itself contains a comma, then the value needs to be enclosed within a delimiter. A delimiter simply tells the software where the value begins and where it ends.

Generally, delimiters are the double-quote character. As I'll show you later, you can specify the delimiter to use when you save a CSV file. But for the examples in this article, the double-quote character will be used for delimiters.

This value,

one, two, and three

because it contains a comma, would be stored in the CSV file as

"one, two, and three"

Now, let's suppose the value itself contains the delimiter character. In that case, the value is delimited, and the delimiter character within the value is doubled up. (The delimiter can also be escaped with a backward slash character, but we'll use doubling-up for this article.)

When formatted for CSV,

my "real" fake foto

would be stored in the CSV file as

"my ""real"" fake foto"

Saving an Array to a CSV File

Here is the code to store the $testing array (way further up in this article) in a CSV file.

<?php
$testing = array( 123, 'abc', 'the "old" tire', "Sadine's nice, spacious elf house" );
$filepointer = fopen('firstTestFile.csv','w');
fputcsv($filepointer,$testing,',','"','');
fclose($filepointer);
?>

The above writes a line of CSV to a file. Some elements are colored blue to help guide your eyes.

The PHP function fputcsv() is used to both convert the array into a line of CSV values and write the line to a file.

Here are the parameters that fputcsv() expects.

  1. A pointer to the file ($filepointer in the above code).

  2. The array to convert to CSV and write to the file (value $testing in the above code).

  3. The value separation character (a comma in the above code).

  4. The delimiter character (a double-quote character in the above code).

  5. The escape character (null in the above code).

The last three parameter values above are what most every CSV-formatted file uses. You may have reason to use different values. But if you do, be aware that some other software may not be able to read your file.

When the above PHP code is run, it creates a file named firstTestFile.csv. The content of the file will be:

123,abc,"the ""old"" tire","Sadine's nice, spacious elf house"

For multi-line files, repeat fputcsv(…) with a new array of data for each array you wish to save to a file.

Reading a CSV file into an Array

For the example code, we'll read the one-line firstTestFile.csv file and display the data as an array.

<php
$filepointer = fopen('firstTestFile.csv','r');
while( ($data=fgetcsv($filepointer,0,',','"','')) !== false )
{
   echo '<pre>'.print_r($data,true).'</pre>';
}
fclose($filepointer);
?>

The above reads the lines of CSV and displays the resulting arrays on the screen. Some elements are colored blue to help guide your eyes.

The PHP function fgetcsv() is used to both read a line from the file and convert the result into an array. The second parameter for fgetcsv() is a maximum line length. If 0 (zero) is used, there is no maximum. The first and the last three parameters for the fgetcsv() function are the same as the first and last three for the fputcsv() function.

The bolded line in the above code displays the array on the screen. For other functionality, replace that line with your own.

This is what the above script will display when it reads the file earlier saved as CSV with the fputcsv() example code further above.

Array
(
    [0] => 123
    [1] => abc
    [2] => the "old" tire
    [3] => Sadine's nice, spacious elf house
)

Once understood and used, the fgetcsv() and fputcsv() functions can become intuitive and simple to use. One formats an array as CSV and saves it to a file. The other reads a CSV file and converts the data into an array.

(This content first appeared in Possibilities newsletter.)

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2026 Will Bontrager Software LLC