My hosting provider doesn't have a version of PHP that supports str_getcsv() so I looked around and found this function. It does the trick except that it gives me an extra empty array and it's messing up my code. Example "a, b, b" would return Array ( [0] => a [1] => b [2] => c [3] => )
. Here's the function:
function _pick_csv_element($x) {
return strlen($x[1]) ? $x[1] : $x[2];
}
function str_getcsv($input) {
preg_match_all(
'/\G (?: \s*"([^"]*)"\s* | ([^,]*) ) (?:,|$) /x',
$input, $matches,
PREG_SET_ORDER
);
return array_map('_pick_csv_element', $matches);
}
Probably the most reliable workaround is this:
$fh = fopen('php://temp', 'r+');
fwrite($fh, $string);
rewind($fh);
$row = fgetcsv($fh);
fclose($fh);
You keep using the built-in CSV function, you just need to make it read from a stream. This has a slight performance hit though, since the string needs to be copied.
Dave,
I guess you're using PHP 5.2.*. If your requirement is to read an entire CSV file into a multi-dimensional associative array, below would work like a beauty:
function parse_csv_file($csvfile) {
$csv = Array();
$rowcount = 0;
if (($handle = fopen($csvfile, "r")) !== FALSE) {
$max_line_length = defined('MAX_LINE_LENGTH') ? MAX_LINE_LENGTH : 10000;
$header = fgetcsv($handle, $max_line_length);
$header_colcount = count($header);
while (($row = fgetcsv($handle, $max_line_length)) !== FALSE) {
$row_colcount = count($row);
if ($row_colcount == $header_colcount) {
$entry = array_combine($header, $row);
$csv[] = $entry;
}
else {
error_log("csvreader: Invalid number of columns at line " . ($rowcount + 2) . " (row " . ($rowcount + 1) . "). Expected=$header_colcount Got=$row_colcount");
return null;
}
$rowcount++;
}
//echo "Totally $rowcount rows found
";
fclose($handle);
}
else {
error_log("csvreader: Could not read CSV \"$csvfile\"");
return null;
}
return $csv;
}
Look here for your answer this may help you lot.