Filip Blaauw
Filip Blaauw

Reputation: 761

How to parse this csv to an array with php

What is the best way to parse this cross domain csv file to an array?

Example data:

2015-03-26 01:00;     1,428;    39,513
2015-03-26 02:00;     1,425;    39,294
2015-03-26 03:00;     1,422;    39,076
2015-03-26 04:00;     1,421;    39,004
2015-03-26 05:00;     1,416;    38,642
2015-03-26 06:00;     1,416;    38,642
2015-03-26 07:00;     1,416;    38,642
2015-03-26 08:00;     1,416;    38,642

I tried something like this:

$file = fopen("http://somedomain.com/data.csv", "r");
while (($buffer = fgets($file)) !== false) {
    $fields = explode(";", $buffer);    
    print_r(fgetcsv($file));
    }    
fclose($file);

But it still splits the data at the comma, not semicolon. I'd be happy for any suggestions!

Upvotes: 1

Views: 66

Answers (1)

Darragh Enright
Darragh Enright

Reputation: 14136

Just use fgetcsv(), specifying ';' as the delimiter in the third argument. For example:

$fh = fopen('data.csv', 'r');

while (false !== ($row = fgetcsv($fh, 1000, ';'))) {
    print_r($row);
}

Yields:

Array
(
    [0] => 2015-03-26 01:00
    [1] =>      1,428
    [2] =>     39,513
)
Array
(
    [0] => 2015-03-26 02:00
    [1] =>      1,425
    [2] =>     39,294
)
Array
(
    [0] => 2015-03-26 03:00
    [1] =>      1,422
    [2] =>     39,076
)
// etc.

Hope this helps :)

Upvotes: 2

Related Questions