I'm trying to parse a CSV string to an array in PHP. The CSV string has the following attributes:
Delimiter: ,
Enclosure: "
New line: \r\n
Example content:
"12345","Computers","Acer","4","Varta","5.93","1","0.04","27-05-2013"
"12346","Computers","Acer","5","Decra","5.94","1","0.04","27-05-2013"
When I try to parse it like this:
$url = "//www.url-to-feed.com";
$csv = file_get_contents[$url];
$data = str_getcsv[$csv];
var_dump[$data];
The last and first element are concatenated in one string:
[0]=> string[5] "12345"
...
[7]=> string[4] "0.04"
[8]=> string[19] "27-05-2013
"12346""
How can I fix this? Any help would be appreciated.
user
20.8k9 gold badges109 silver badges98 bronze badges
asked Jul 20, 2013 at 10:18
2
Do this:
$csvData = file_get_contents[$fileName];
$lines = explode[PHP_EOL, $csvData];
$array = array[];
foreach [$lines as $line] {
$array[] = str_getcsv[$line];
}
print_r[$array];
It will give you an output like this:
Array
[
[0] => Array
[
[0] => 12345
[1] => Computers
[2] => Acer
[3] => 4
[4] => Varta
[5] => 5.93
[6] => 1
[7] => 0.04
[8] => 27-05-2013
]
[1] => Array
[
[0] => 12346
[1] => Computers
[2] => Acer
[3] => 5
[4] => Decra
[5] => 5.94
[6] => 1
[7] => 0.04
[8] => 27-05-2013
]
]
I hope this can be of some help.
answered Jul 20, 2013 at 10:44
saran banerjeesaran banerjee
2,8251 gold badge12 silver badges12 bronze badges
11
You should use
fgetcsv. Since you cannot import a file as a stream because the csv is a variable, then you should spoof the string as a file by using php://temp
or php://memory
first:
$fp = fopen["php://temp", 'r+'];
fputs[$fp, $csvText];
rewind[$fp];
Then you will have no problem using fgetcsv:
$csv = [];
while [ [$data = fgetcsv[$fp] ] !== FALSE ] {
$csv[] = $data;
}
fclose[$fp]
$data
will be an array of a single csv line [which may include line breaks or commas, etc], as it should be.
Caveat: The memory limit of php://temp can be controlled by appending /maxmemory:NN, where NN is the maximum amount of data to keep in memory before using a temporary file, in bytes. [the default is 2 MB] //www.php.net/manual/en/wrappers.php.php
answered Jun 9, 2017 at 3:43
iateadonutiateadonut
1,66416 silver badges27 bronze badges
7
Handy oneliner:
$csv = array_map['str_getcsv', file['data.csv']];
answered Dec 10, 2014 at 20:44
GauiGaui
8,46315 gold badges63 silver badges88 bronze badges
8
I have used following function to parse csv string to associative array
public function csvToArray[$file] {
$rows = array[];
$headers = array[];
if [file_exists[$file] && is_readable[$file]] {
$handle = fopen[$file, 'r'];
while [!feof[$handle]] {
$row = fgetcsv[$handle, 10240, ',', '"'];
if [empty[$headers]]
$headers = $row;
else if [is_array[$row]] {
array_splice[$row, count[$headers]];
$rows[] = array_combine[$headers, $row];
}
}
fclose[$handle];
} else {
throw new Exception[$file . ' doesn`t exist or is not readable.'];
}
return $rows;
}
if your csv file name is mycsv.csv then you call this function as:
$dataArray = csvToArray[mycsv.csv];
you can get this script also in //www.scriptville.in/parse-csv-data-to-array/
answered Sep 22, 2014 at 15:27
1
A modification of previous
answers using array_map
.
Blow up the CSV data with multiple lines.
$csv = array_map['str_getcsv', explode["\n", $csvData]];
answered May 11, 2018 at 23:08
Joseph D.Joseph D.
11.2k3 gold badges29 silver badges62 bronze badges
Slightly shorter version, without unnecessary second variable:
$csv = rows[];
foreach [$rows as $row]
{
// do something with $row
}
answered Oct 4, 2018 at 10:20
Stacey RichardsStacey Richards
6,4267 gold badges37 silver badges40 bronze badges
You can convert CSV string to Array with this function.
function csv2array[
$csv_string,
$delimiter = ",",
$skip_empty_lines = true,
$trim_fields = true,
$FirstLineTitle = false
] {
$arr = array_map[
function [ $line ] use [ &$result, &$FirstLine, $delimiter, $trim_fields, $FirstLineTitle ] {
if [$FirstLineTitle && !$FirstLine] {
$FirstLine = explode[ $delimiter, $result[0] ];
}
$lineResult = array_map[
function [ $field ] {
return str_replace[ '!!Q!!', '"', utf8_decode[ urldecode[ $field ] ] ];
},
$trim_fields ? array_map[ 'trim', explode[ $delimiter, $line ] ] : explode[ $delimiter, $line ]
];
return $FirstLineTitle ? array_combine[ $FirstLine, $lineResult ] : $lineResult;
},
[$result = preg_split[
$skip_empty_lines ? [ $trim_fields ? '/[ *\R]+/s' : '/\R+/s' ] : '/\R/s',
preg_replace_callback[
'/"[.*?]"/s',
function [ $field ] {
return urlencode[ utf8_encode[ $field[1] ] ];
},
$enc = preg_replace[ '/[?$delimiter = ",";
$enclosure = '"';
$escape = "\\" ;
$rows = array_filter[explode[PHP_EOL, $content]];
$header = NULL;
$data = [];
foreach[$rows as $row]
{
$row = str_getcsv [$row, $delimiter, $enclosure , $escape];
if[!$header] {
$header = $row;
} else {
$data[] = array_combine[$header, $row];
}
}
answered Apr 9, 2020 at 14:54
1