1

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!

2
  • Have a look at the documentation, you need to pass a 3rd param of ; to get it to split by a semi-colon. Commented May 24, 2015 at 22:59
  • Actually your code works fine. add print_r($fields) and you will see the actual result of splitting at your specified delimiter. Commented May 25, 2015 at 0:52

1 Answer 1

2

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 :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.