note 109986 added to function.str-getcsv
| From: | dan dot gruenzig at snailsites dot com | Date: | Fri, 07 Sep 2012 21:44:37 +0000 |
| Subject: | note 109986 added to function.str-getcsv | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-190579@lists.php.net to get a copy of this message | ||
just added some improvements to the function of khelibert@gmail.com
<?php
/**
* Converts a csv file into an array of lines and columns.
* @author khelibert@gmail.com
* @author dan.gruenzig@snailsites.com
* @param $_fileContent String
* @param string $_escape String
* @param string $_enclosure String
* @param string $_delimiter String
* @return array
*/
function csvToArray ( $_fileContent, $_escape = '\\', $_enclosure = '"',
$_delimiter = ';') {
$ret = array();
$fields = array();
$content_formated = '';
if ($_escape == $_enclosure) {
$_escape = '\\';
$content_formated = str_replace(
array('\\',$_enclosure.$_enclosure,"\r\n","\r")
,array('\\\\',$_escape.$_enclosure,"\\n","\\n")
,$_fileContent
);
}
else {
$content_formated = str_replace(
array("\r\n","\r")
,array("\\n","\\n")
,$_fileContent
);
}
$nb = strlen($content_formated);
$field = '';
$inEnclosure = false;
$previous = '';
for ($i = 0;$i<$nb; $i++) {
$c = $content_formated[$i];
switch ($c) {
case $_enclosure:
if ($previous !== $_escape) {
$inEnclosure ^= true;
}
else {
$field .= $_enclosure;
}
break;
case $_escape:
$next = $content_formated[$i+1];
if (
$next != $_enclosure
&& $next != $_escape
) {
$field .= $_escape;
}
break;
case $_delimiter:
if ($inEnclosure) {
$field .= $_delimiter;
}
else {
//end of the field
$fields[] = $field;
$field = '';
}
break;
case "n":
if (
$previous==$_escape
&& !$inEnclosure
) {
$fields[] = substr($field,0,-1);
$field = '';
$ret[] = $fields;
$fields = array();
break;
}
default:
$field .= $c;
}
$previous = $c;
}
if ($field!=='') {
$fields[] = $field;
}
if ($fields) {
$ret[] = $fields;
}
return $ret;
}
?>
----
Server IP: 69.147.83.197
Probable Submitter: 79.193.134.106
----
Manual Page -- http://www.php.net/manual/en/function.str-getcsv.php
Edit -- https://master.php.net/note/edit/109986
Del: integrated -- https://master.php.net/note/delete/109986/integrated
Del: useless -- https://master.php.net/note/delete/109986/useless
Del: bad code -- https://master.php.net/note/delete/109986/bad+code
Del: spam -- https://master.php.net/note/delete/109986/spam
Del: non-english -- https://master.php.net/note/delete/109986/non-english
Del: in docs -- https://master.php.net/note/delete/109986/in+docs
Del: other reasons-- https://master.php.net/note/delete/109986
Reject -- https://master.php.net/note/reject/109986
Search -- https://master.php.net/manage/user-notes.php