Jens Törnell Jens Törnell - 2 months ago 25
PHP Question

PHP csv string parsing

I have a PHP CSV file that looks like this:

'numberOfProducts' 'lastUpdated'
'28' '2016-09-19 06:55'


I tried to do like this:

print_r( str_getcsv( $csv, "\n", "\t" ) );
print_r( str_getcsv( $csv, "\t", "\n" ) );


It's just a mess.

Expected result



But my expected result should be something like this:

'numberOfProducts' => '28'
'lastUpdated' => '2016-09-19 06:55'


Is it possible with str_getcsv or is it easier with explode?

Result



The is my result:

Array
(
[0] => numberOfProducts
[1] => lastUpdated
'28'
[2] => 2016-09-19 06:55
)


Not like my expected result.

Answer

"str_getcsv" only parse one row at a time:

You need to run it for each row:

$rows = explode("\n", $csv);
foreach($rows as $row){
    print_r( str_getcsv( $row, "\t", "'") );
}