note 97808 modified in function.str-getcsv by danbrown
| From: | danbrown@php.net | Date: | Mon, 10 May 2010 12:14:08 +0000 |
| Subject: | note 97808 modified in function.str-getcsv by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-169121@lists.php.net to get a copy of this message | ||
I found myself wanting to parse a CSV and didn't have access to str_getcsv, so I wrote
substitute for PHP <= 5.3, hope it helps someone out there stuck in the same situation.
<?php
if (!function_exists('str_getcsv')) {
function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape =
'\\', $eol = "\n") {
if (is_string($input) && !empty($input)) {
$output = array();
$tmp = preg_split("/".$eol."/",$input);
if (is_array($tmp) && !empty($tmp)) {
while (list($line_num, $line) = each($tmp)) {
if (preg_match("/".$escape.$enclosure."/",$line)) {
for ($i=0;$i<strlen($line);$i++) {
$pos_delimiter = strpos($line,$delimiter);
$pos_enclosure_start = strpos($line,$enclosure);
if ($pos_enclosure_start < $pos_delimiter) {
$enclosed_str = substr($line,1);
$pos_enclosure_end = strpos($enclosed_str,$enclosure);
$enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
$output[$line_num][] = $enclosed_str;
$offset = $pos_enclosure_end+3;
} else {
$output[$line_num][] = substr($line,0,$pos_delimiter);
$offset = $pos_delimiter+1;
}
$line = substr($line,$offset);
}
} else {
$output[$line_num] = preg_split("/".$delimiter."/",$line);
}
}
return $output;
} else {
return false;
}
} else {
return false;
}
}
}
?>
--was--
I found myself wanting to parse a CSV and didn't have access to str_getcsv, so I wrote
substitute for PHP <= 5.3, hope it helps someone out there stuck in the same situation.
if (!function_exists('str_getcsv')) {
function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape =
'\\', $eol = "\n") {
if (is_string($input) && !empty($input)) {
$output = array();
$tmp = preg_split("/".$eol."/",$input);
if (is_array($tmp) && !empty($tmp)) {
while (list($line_num, $line) = each($tmp)) {
if (preg_match("/".$escape.$enclosure."/",$line)) {
for ($i=0;$i<strlen($line);$i++) {
$pos_delimiter = strpos($line,$delimiter);
$pos_enclosure_start = strpos($line,$enclosure);
if ($pos_enclosure_start < $pos_delimiter) {
$enclosed_str = substr($line,1);
$pos_enclosure_end = strpos($enclosed_str,$enclosure);
$enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
$output[$line_num][] = $enclosed_str;
$offset = $pos_enclosure_end+3;
} else {
$output[$line_num][] = substr($line,0,$pos_delimiter);
$offset = $pos_delimiter+1;
}
$line = substr($line,$offset);
}
} else {
$output[$line_num] = preg_split("/".$delimiter."/",$line);
}
}
return $output;
} else {
return false;
}
} else {
return false;
}
}
}
http://php.net/manual/en/function.str-getcsv.php