note 106888 added to function.str-getcsv

From: Date: Thu, 15 Dec 2011 20:53:51 +0000
Subject: note 106888 added to function.str-getcsv
Groups: php.notes 
Request: Send a blank email to php-notes+get-185081@lists.php.net to get a copy of this message
Here's a piece of code that parses Excel CSV correctly. <?php function parse_csv($file,$comma=',',$quote='"',$newline="\n") { $db_quote = $quote . $quote; // Clean up file $file = trim($file); $file = str_replace("\r\n",$newline,$file); $file = str_replace($db_quote,'&quot;',$file); // replace double quotes with &quot; HTML entities $file = str_replace(',&quot;,',',,',$file); // handle ,"", empty cells correctly $file .= $comma; // Put a comma on the end, so we parse last cell $inquotes = false; $start_point = 0; $row = 0; for($i=0; $i<strlen($file); $i++) { $char = $file[$i]; if ($char == $quote) { if ($inquotes) { $inquotes = false; } else { $inquotes = true; } } if (($char == $comma or $char == $newline) and !$inquotes) { $cell = substr($file,$start_point,$i-$start_point); $cell = str_replace($quote,'',$cell); // Remove delimiter quotes $cell = str_replace('&quot;',$quote,$cell); // Add in data quotes $data[$row][] = $cell; $start_point = $i + 1; if ($char == $newline) { $row ++; } } } return $data; } $file ='Year,Make,Model,Description,Price 1997,Ford,E350,"ac, abs, moon",3000.00 1999,Chevy,"Venture ""Extended Edition""","",4900.00 1999,Chevy,"Venture ""Extended Edition, Very Large""","",5000.00 1996,Jeep,Grand Cherokee,"MUST SELL! air, moon roof, loaded",4799.00'; print_r(parse_csv($file)); // Returns what you'd expect. See http://en.wikipedia.org/wiki/Comma-separated_values for example ?> ---- Server IP: 117.55.229.1 Probable Submitter: 101.170.74.77 ---- Manual Page -- http://www.php.net/manual/en/function.str-getcsv.php Edit -- https://master.php.net/note/edit/106888 Del: integrated -- https://master.php.net/note/delete/106888/integrated Del: useless -- https://master.php.net/note/delete/106888/useless Del: bad code -- https://master.php.net/note/delete/106888/bad+code Del: spam -- https://master.php.net/note/delete/106888/spam Del: non-english -- https://master.php.net/note/delete/106888/non-english Del: in docs -- https://master.php.net/note/delete/106888/in+docs Del: other reasons-- https://master.php.net/note/delete/106888 Reject -- https://master.php.net/note/reject/106888 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#185081) next »