Jens Törnell Jens Törnell - 1 year ago 142
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?


The is my result:

[0] => numberOfProducts
[1] => lastUpdated
[2] => 2016-09-19 06:55

Not like my expected result.

Answer Source

"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", "'") );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download