Should I use "fgetcsv" instead of "array_map" and how to do it?

240 Views Asked by At

I've made this script to extract data from a CSV file.

$url = 'https://flux.netaffiliation.com/feed.php?maff=3E9867FCP3CB0566CA125F7935102835L51118FV4';
$data = array_map(function($line) { return str_getcsv($line, '|'); }, file($url));

It's working exactly as I want but I've just been told that it's not the proper way to do it and that I really should use fgetcsv instead.

Is it right ? I've tried many ways to do it with fgetcsv but didn't manage at all to get anything close.

Here is an example of what i would like to get as an output :

$data[4298][0] = 889698467841
$data[4298][1] = Figurine Funko Pop! - N° 790 - Disney : Mighty Ducks - Coach Bombay
$data[4298][2] = 108740
$data[4298][3] = 14.99
1

There are 1 best solutions below

3
Selim Acar On

First of all, there is no the ONE proper way to do things in programming. It is up to you and depends on your use case.

I just downloaded the CSV file and it is ca. 20MB big. In your solution you download the whole file at once. If you do not have any memory restrictions and you do not have to give a fast feedback to the caller, I mean if the delay for downloading of the whole file is not important, your solution is better solution, if you want to guarantee the processing of the whole content. In this case, you read all the content at once and the further processing of the content does not depend on other things like your Internet connection etc.

If you want to use fgetcsv, you would read from the URL line by line squentially. Your connection has to remain until a line has been processed. In this you do not need big memory allocation but it would take longer to having processed the whole content.

Both methods have their pros and contras. You should know what is your goal. How often would you run this script? You should consider your use case and make a decision which method is the best for you.

Here is the same result without array_map():

$url = 'https://flux.netaffiliation.com/feed.php?maff=3E9867FCP3CB0566CA125F7935102835L51118FV4';
$lines = file($url);
$data = [];
foreach($lines as $line)
{
    $data[] = str_getcsv(trim($line), '|');
    //optionally:
    //$data[] = explode('|',trim($line));

}
$lines = null;