note 86879 added to function.str-getcsv

From: Date: Fri, 07 Nov 2008 16:54:04 +0000
Subject: note 86879 added to function.str-getcsv
Groups: php.notes 
Request: Send a blank email to php-notes+get-146290@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. 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; } ---- Server IP: 64.71.164.2 Probable Submitter: 64.102.157.165 ---- Manual Page -- http://www.php.net/manual/en/function.str-getcsv.php Edit -- https://master.php.net/note/edit/86879 Del: integrated -- https://master.php.net/note/delete/86879/integrated Del: useless -- https://master.php.net/note/delete/86879/useless Del: bad code -- https://master.php.net/note/delete/86879/bad+code Del: spam -- https://master.php.net/note/delete/86879/spam Del: non-english -- https://master.php.net/note/delete/86879/non-english Del: in docs -- https://master.php.net/note/delete/86879/in+docs Del: other reasons-- https://master.php.net/note/delete/86879 Reject -- https://master.php.net/note/reject/86879 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#146290) next »