HomeBlogWhy you should use fgetcsv() instead of explode

Why you should use fgetcsv() instead of explode

Published March 17, 2006
Some programmers think it is okay to use explode to split up a CSV file (usually a csv file is comma separated but sometimes it is tab separated or even some other separator is used). The reason it is a bad idea to use a simple explode is because your data can easily contain the separator in the content. This is very very common with comma's. Here is a quick example of data that excel would return when converting a sheet to CSV. id, name, address 1,james,100 smith street 2,billy,"200 smith street, apt 2" As you can see on the 3rd line (2nd line of data) excel was smart enough, as should any program that creates a csv file, to quote the column that has the separator that is being used. When doing an explode on the information above we are going to get 4 columns on the 3rd line instead of 3 columns and the content of those 4 columns will be column 1: 2 column 2: billy column 3: "200 smith street column 4: apt 2" Where if fgetcsv() was used, a function built into php, you would get the following columns column 1: 2 column 2: billy column 3: 200 smith street, apt2 So as you can see we get the data how we want it and it even removes the quotes that were not there originally. Happy Coding!
blog comments powered by Disqus

1 OLDER COMMENT

posted by Jaimie Sirovich on: Mar 27, 2006 06:50pm

Use this to create well-formed CSVs, and use an escape function that doubles up "'s. This is another common mistake people make. function escapeMS($string) { return str_replace('"', '""', $string); } function quotedImplode($glue, $array, $quote_char = "'", $escape_function = "addslashes") { foreach ($array as $i => $a) { $array[$i] = $quote_char . $escape_function($array[$i]) . $quote_char; } return implode($glue, $array); }

1 COMMENT

Matt

Matthew came to RustyBrick in 2004 after spending multiple years developing large-scale web applications. He graduated with a B.S. in Computer Science from the University of Hartford.

This article is under PHP Programming

There is 1 comment for this post

Connect With Us

Send Us a Message

Do you wish to give us feedback on one of our apps, send us a message or explore a proposal? Fill out the form below and we'll get back to you pronto!

Visit Us

250 West Nyack Road, Suite #200 West Nyack, NY 10994
Get Directions

Call Us Toll Free

877-GO-RUSTY
877-467-8789

Telephone

845-369-6869

Fax

845-228-8177