Parse a CSV file line in PHP

Posted by on March 8, 2012 in PHP, Programming | 0 comments

Parse a CSV file line in PHP

PHP has great string manipulation tools for importing files like fgets() to get a single line or file() to dump the lines into an array right at import. Explode is a great function when you start dealing with the contents of the file. However, if you’re bringing in a standardized file, like a CSV, there are some issues with explode. For instance, a comma may be in a string in the middle of the field, so you can’t break it apart on commas. You could try to split the CSV line on the double quotes, but if the field is an integer, there won’t be quotes around it. You need to use a regular expression (regex) to get your desired array.

How to get an array of the fields out of a CSV file line.

function csvLineExplode($line)
{
$pattern = ‘/(,)(?=(?:[^”]|”[^”]*”)*$)/';
$replacement = ‘|ABn23SQyU|';
$replacement2 = ‘|Q8Nhsd90kSh|';
$line2 = preg_replace($pattern, $replacement, $line);
$line2 = str_replace(‘””‘, $replacement2, $line2);
$line2 = str_replace(‘”‘, ”, $line2);
$line2 = str_replace($replacement2, ‘”‘, $line2);
$lineEx = explode($replacement, $line2);
return $lineEx;
}

Explanation

  • $pattern – This is the key to replacing only the commas between elements.
  • $replacement(2) – These can be any string that isn’t going to appear in the fields.
  • $preg_replace() – This is the step that replaces the commas between elements with a replaceable character to explode on.
  • str_replace – Double quotes that appear in fields are converted to a double double quote “”. ┬áReplace these doubles before removing the outer quotes around the field.
  • str_replace – Replace the outer quotes of the fields with nothing so it’s a clean element.
  • str_replace – Put the quotes that were part of the field text back into the string.
  • explode – Break apart the string into an array on the original field separators.

If there are any cases I overlooked, please list them in the comments and I’ll try and update this.

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>