Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
CSV is a very popular format for importing and exporting data to and from databases and spreadsheets. We will be using some built in PHP functions that lets us read and write CSV data as arrays.
Other Formats for CSV
It is not required that CSV files have a header line, although the SHOULD. Also, any character can be used as a delimiter to separate columns. Other common delimiters include pipe (|) and tab (\t). If your CSV file uses a different delimiter, make sure you specify the delimiter in the options of fgetcsv.
Additional fgetcsv Options
Besides passing the file handler, you can also specify
length Must be greater than the longest line (in characters) to be found in the CSV file (allowing for trailing line-end characters). Otherwise the line is split in chunks of length characters, unless the split would occur inside an enclosure.
Omitting this parameter (or setting it to 0 in PHP 5.1.0 and later) the maximum line length is not limited, which is slightly slower.
delimiter The optional delimiter parameter sets the field delimiter (one character only).
enclosure The optional enclosure parameter sets the field enclosure character (one character only, like a single or double quote).
escape The optional escape parameter sets the escape character (one character only).
Read the Documentation: fgetcsv
Checking if File is Open
I have shown two ways to check if a file is open
if ($fh = fopen(FILE, MODE)) {
Is the same as
if (($fh = fopen(FILE, MODE)) !== false) {
because the if statement is checking for a "truthy" (meaning positive) value. If the file is open the value is "truthy", and if the $fh !== false, this is also a positive value.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up