note 87729 modified in function.fgetcsv by danbrown
| From: | danbrown@php.net | Date: | Thu, 18 Dec 2008 14:42:02 +0000 |
| Subject: | note 87729 modified in function.fgetcsv by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-148313@lists.php.net to get a copy of this message | ||
Here is a script that convert a CSV to an double-array ([row][col]), none of the ones below works in
my case. (Multi-line, quoted or not, ...) It use coma as field separator, and double-quote.
<?php
$fileContent = file_get_contents("my_file.csv");
//Convert Windows CR to Linux
$fileContent = str_replace("\r\n","\n",$fileContent);
//Split file by finding right CR.
$expr="/\n(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/";
$rows=preg_split($expr,trim($fileContent));
unset($fileContent); //Free up some memory
$data = array();
foreach($rows as $row){
//Find right coma
$expr="/,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/";
$results = preg_split($expr,trim($row));
//Remove quote
$data[] = preg_replace("/\"(.*)\"/s","$1",$results);
}
unset($rows); //Free up some memory
//Show the result
echo "<pre>";
print_r($data);
echo "</pre>";
?>
--was--
Here is a script that convert a CSV to an double-array ([row][col]), none of the ones below works in
my case. (Multi-line, quoted or not, ...) It use coma as field separator, and double-quote.
$fileContent = file_get_contents("my_file.csv");
//Convert Windows CR to Linux
$fileContent = str_replace("\r\n","\n",$fileContent);
//Split file by finding right CR.
$expr="/\n(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/";
$rows=preg_split($expr,trim($fileContent));
unset($fileContent); //Free up some memory
$data = array();
foreach($rows as $row){
//Find right coma
$expr="/,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/";
$results = preg_split($expr,trim($row));
//Remove quote
$data[] = preg_replace("/\"(.*)\"/s","$1",$results);
}
unset($rows); //Free up some memory
//Show the result
echo "<pre>";
print_r($data);
echo "</pre>";
http://php.net/manual/en/function.fgetcsv.php