note 86879 modified in function.str-getcsv by danbrown

From: Date: Mon, 19 Jan 2009 17:33:41 +0000
Subject: note 86879 modified in function.str-getcsv by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-149471@lists.php.net to get a copy of this message
This does the same as the example below, giving you an array, but it allows to parse csv with commas in between quotes (used for addresses)... and it takes out the quotes from an array entry as well. <?php function parse_csv($file, $options = null) { $delimiter = empty($options['delimiter']) ? "," : $options['delimiter']; $to_object = empty($options['to_object']) ? false : true; $expr="/$delimiter(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/"; // added $str = $file; $lines = explode("\n", $str); $field_names = explode($delimiter, array_shift($lines)); foreach ($lines as $line) { // Skip the empty line if (empty($line)) continue; $fields = preg_split($expr,trim($line)); // added $fields = preg_replace("/^\"(.*)\"$/","$1",$fields); //added //$fields = explode($delimiter, $line); $_res = $to_object ? new stdClass : array(); foreach ($field_names as $key => $f) { if ($to_object) { $_res->{$f} = $fields[$key]; } else { $_res[$f] = $fields[$key]; } } $res[] = $_res; } return $res; } ?> [EDIT BY danbrown AT php DOT net: Includes a bugfix provided by "Anonymous" on 12-JAN-09.] --was-- This does the same as the example below, giving you an array, but it allows to parse csv with commas in between quotes (used for addresses)... and it takes out the quotes from an array entry as well. <?php function parse_csv($file, $options = null) { $delimiter = empty($options['delimiter']) ? "," : $options['delimiter']; $to_object = empty($options['to_object']) ? false : true; $expr="/,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/"; // added $str = $file; $lines = explode("\n", $str); $field_names = explode($delimiter, array_shift($lines)); foreach ($lines as $line) { // Skip the empty line if (empty($line)) continue; $fields = preg_split($expr,trim($line)); // added $fields = preg_replace("/^\"(.*)\"$/","$1",$fields); //added //$fields = explode($delimiter, $line); $_res = $to_object ? new stdClass : array(); foreach ($field_names as $key => $f) { if ($to_object) { $_res->{$f} = $fields[$key]; } else { $_res[$f] = $fields[$key]; } } $res[] = $_res; } return $res; } ?> http://php.net/manual/en/function.str-getcsv.php

« previous php.notes (#149471) next »