note 72749 deleted from function.fgetcsv by danbrown
| From: | danbrown@php.net | Date: | Sun, 17 May 2009 18:11:39 +0000 |
| Subject: | note 72749 deleted from function.fgetcsv by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-155078@lists.php.net to get a copy of this message | ||
Note Submitter:
----
just another csv file parse function
<?php
define('CSV_BOTH', 1);
define('CSV_ASSOC', 2);
define('CSV_NUM', 3);
function parse_csv($filename, $result_type = CSV_BOTH) {
if(!file_exists($filename)) {
die("file (" . $filename . ") does not exist\n");
}
$lines = file($filename);
$title_line = trim(array_shift($lines));
$titles = split(",", $title_line);
$records = array();
foreach($lines as $line_num => $line) {
$subject = trim($line);
$fields = array();
for($field_num = 0; $field_num < count($titles); $field_num++) {
if($subject{0} == '"') {
preg_match('/^"(([^"]|\\")*)",?(.*)$/', $subject, $matches);
$value = $matches[1];
$subject = $matches[3];
if($result_type == CSV_BOTH || $result_type == CSV_ASSOC) {
$fields[$titles[$field_num]] = $value;
}
if($result_type == CSV_BOTH || $result_type == CSV_NUM) {
$fields[$field_num] = $value;
}
} else {
preg_match('/^([^,]*),?(.*)$/', $subject, $matches);
$value = $matches[1];
$subject = $matches[2];
if($result_type == CSV_BOTH || $result_type == CSV_ASSOC) {
$fields[$titles[$field_num]] = $value;
}
if($result_type == CSV_BOTH || $result_type == CSV_NUM) {
$fields[$field_num] = $value;
}
}
}
$records[] = $fields;
}
return $records;
}
?>