Viewed   110 times

I'm trying to parse a CSV string to an array in PHP. The CSV string has the following attributes:

Delimiter: ,
Enclosure: "
New line: rn

Example content:

"12345","Computers","Acer","4","Varta","5.93","1","0.04","27-05-2013"
"12346","Computers","Acer","5","Decra","5.94","1","0.04","27-05-2013"

When I try to parse it like this:

$url = "http://www.url-to-feed.com";
$csv = file_get_contents($url);
$data = str_getcsv($csv);
var_dump($data);

The last and first element are concatenated in one string:

[0]=> string(5) "12345"
...
[7]=> string(4) "0.04"
[8]=> string(19) "27-05-2013
"12346""

How can I fix this? Any help would be appreciated.

 Answers

5

Do this:

$csvData = file_get_contents($fileName);
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) {
    $array[] = str_getcsv($line);
}
print_r($array);

It will give you an output like this:

Array
(
    [0] => Array
        (
            [0] => 12345
            [1] => Computers
            [2] => Acer
            [3] => 4
            [4] => Varta
            [5] => 5.93
            [6] => 1
            [7] => 0.04
            [8] => 27-05-2013
        )

    [1] => Array
        (
            [0] => 12346
            [1] => Computers
            [2] => Acer
            [3] => 5
            [4] => Decra
            [5] => 5.94
            [6] => 1
            [7] => 0.04
            [8] => 27-05-2013
        )

)

I hope this can be of some help.

Saturday, October 8, 2022
1

When i needed to work with files that big I always use the 'divide and conquer' premise. For your case I would:

  • Dynamicaly create a folder
  • Copy this big file inside it
  • Split it (on linux split called from php) split command
  • use the shell_exec command in php
  • After split it, delete it (the big file)
  • Then loop through the files in the folder reading one by one.
  • And for every file I finish I delete it. So if the time limit occurs you will need just to continue reading the files left in the folder.
  • Friday, September 16, 2022
     
    echo
     
    4

    Try this php code (gets the lines with file()).:

    <?php
    $csv1 = file('csv1.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $csv2 = file('csv2.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $csv3 = file('csv3.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $lines = max(count($csv1), count($csv2), count($csv3));
    $finalcsv = array();
    for($i=0; $i<$lines; $i++) {
      if(isset($csv1[$i])) $finalcsv[] = $csv1[$i];
      if(isset($csv2[$i])) $finalcsv[] = $csv2[$i];
      if(isset($csv3[$i])) $finalcsv[] = $csv3[$i];
    }
    
    file_put_contents('final_data.csv', implode(PHP_EOL, $finalcsv));
    
    Friday, September 16, 2022
     
    vectran
     
    5

    You can convert a string to a file object using io.StringIO and then pass that to the csv module:

    from io import StringIO
    import csv
    
    scsv = """text,with,Polish,non-Latin,letters
    1,2,3,4,5,6
    a,b,c,d,e,f
    g??,zó?ty,w??,idzie,w?sk?,dró?k?,
    """
    
    f = StringIO(scsv)
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        print('t'.join(row))
    

    simpler version with split() on newlines:

    reader = csv.reader(scsv.split('n'), delimiter=',')
    for row in reader:
        print('t'.join(row))
    

    Or you can simply split() this string into lines using n as separator, and then split() each line into values, but this way you must be aware of quoting, so using csv module is preferred.

    On Python 2 you have to import StringIO as

    from StringIO import StringIO
    

    instead.

    Friday, November 18, 2022
     
    g-newa
     
    1

    I would suggest to flatten each array first:

    foreach ($csv as $file) {
        $result = [];
        array_walk_recursive($file, function($item) use (&$result) {
            $result[] = $item;
        });
        fputcsv($output, $result);
    }
    

    In each iteration it would create an array like this:

    [1111, 'Alcatel One Touch Idol 2', 'alcatel-one-touch-idol-2', 54, 42, ...]
    
    Friday, November 4, 2022
     
    clawish
     
    Only authorized users can answer the search term. Please sign in first, or register a free account.
    Not the answer you're looking for? Browse other questions tagged :