note 109945 added to function.fgetcsv

From: Date: Tue, 04 Sep 2012 15:19:59 +0000
Subject: note 109945 added to function.fgetcsv
Groups: php.notes 
Request: Send a blank email to php-notes+get-190492@lists.php.net to get a copy of this message
I've written this to handle : - fields with or without enclosure; - escape and enclosure characters using the same character (ie <<">> in Excel) <?php /** * Converts a csv file into an array of lines and columns. * khelibert@gmail.com * @param $fileContent String * @param string $escape String * @param string $enclosure String * @param string $delimiter String * @return array */ function csvToArray($fileContent,$escape = '\\', $enclosure = '"', $delimiter = ';') { $lines = array(); $fields = array(); if($escape == $enclosure) { $escape = '\\'; $fileContent = str_replace(array('\\',$enclosure.$enclosure,"\r\n","\r"),array('\\\\',$escape.$enclosure,"\\n","\\n"),$fileContent); } else $fileContent = str_replace(array("\r\n","\r"),array("\\n","\\n"),$fileContent); $nb = strlen($fileContent); $field = ''; $inEnclosure = false; $previous = ''; for($i = 0;$i<$nb; $i++) { $c = $fileContent[$i]; if($c === $enclosure) { if($previous !== $escape) $inEnclosure ^= true; else $field .= $enclosure; } else if($c === $escape) { $next = $fileContent[$i+1]; if($next != $enclosure && $next != $escape) $field .= $escape; } else if($c === $delimiter) { if($inEnclosure) $field .= $delimiter; else { //end of the field $fields[] = $field; $field = ''; } } else if($c === "\n") { $fields[] = $field; $field = ''; $lines[] = $fields; $fields = array(); } else $field .= $c; $previous = $c; } //we add the last element if(true || $field !== '') { $fields[] = $field; $lines[] = $fields; } return $lines; } ?> ---- Server IP: 69.147.83.197 Probable Submitter: 82.224.164.252 ---- Manual Page -- http://www.php.net/manual/en/function.fgetcsv.php Edit -- https://master.php.net/note/edit/109945 Del: integrated -- https://master.php.net/note/delete/109945/integrated Del: useless -- https://master.php.net/note/delete/109945/useless Del: bad code -- https://master.php.net/note/delete/109945/bad+code Del: spam -- https://master.php.net/note/delete/109945/spam Del: non-english -- https://master.php.net/note/delete/109945/non-english Del: in docs -- https://master.php.net/note/delete/109945/in+docs Del: other reasons-- https://master.php.net/note/delete/109945 Reject -- https://master.php.net/note/reject/109945 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#190492) next »