note 115226 added to function.file
| From: | marco dot remy at aol dot com | Date: | Tue, 17 Jun 2014 07:54:25 +0000 |
| Subject: | note 115226 added to function.file | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-199693@lists.php.net to get a copy of this message | ||
Here's my CSV converter
supports Header and trims all fields
Note: Headers must be not empty!
<?php
function csv2array($file, $delim = ';', $encl = '"', $header = false) {
# File does not exist
if(!file_exists($file))
return false;
# Read lines of file to array
$file_lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
# Empty file
if($file_lines === array())
return NULL;
# Read headers if you want to
if($header === true) {
$line_header = array_shift($file_lines);
$array_header = array_map('trim', str_getcsv($line_header, $delim, $encl));
}
$out = NULL;
# Now line per line (strings)
foreach ($file_lines as $line) {
# Skip empty lines
if(trim($line) === '')
continue;
# Convert line to array
$array_fields = array_map('trim', str_getcsv($line, $delim, $encl));
# If header present, combine header and fields as key => value
if($header === true)
$out[] = array_combine ($array_header, $array_fields);
else
$out[] = $array_fields;
}
return $out;
}
?>
----
Server IP: 72.52.91.14
Probable Submitter: 213.217.118.51
----
Manual Page -- http://php.net/manual/en/function.file.php
Edit -- https://master.php.net/note/edit/115226
Del: integrated -- https://master.php.net/note/delete/115226/integrated
Del: useless -- https://master.php.net/note/delete/115226/useless
Del: bad code -- https://master.php.net/note/delete/115226/bad+code
Del: spam -- https://master.php.net/note/delete/115226/spam
Del: non-english -- https://master.php.net/note/delete/115226/non-english
Del: in docs -- https://master.php.net/note/delete/115226/in+docs
Del: other reasons-- https://master.php.net/note/delete/115226
Reject -- https://master.php.net/note/reject/115226
Search -- https://master.php.net/manage/user-notes.php