Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any workarounds for the PHP fgetcsv bug where whitespace is trimmed?

Tags:

php

csv

Given the following string of CSV data (I am unable to ensure the fields are quoted)

AB,CD,   EF,GH,   IJ

and PHP code of:

$arr = fgetcsv($f);

(assuming $f is a valid file-pointer reading a file containing the above text) - one would expect this result:

Array('AB', 'CD', '   EF', 'GH', '   IJ');

when in fact you get:

Array('AB', 'CD', 'EF', 'GH', 'IJ');

This is problematic if you need positional context within that field.

Any workarounds of still being able to take advantage of fgetcsv, but ensuring that whitespace is not lost?

The bug is reported here: http://bugs.php.net/bug.php?id=53848

like image 324
drowe Avatar asked Apr 20 '11 22:04

drowe


People also ask

What does Fgetcsv do in php?

The fgetcsv() function parses a line from an open file, checking for CSV fields.

How do you check csv file is empty or not in php?

PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true.

How do I read a csv file in column wise in php?

You can open the file using fopen() as usual, get each line by using fgets() and then simply explode it on each comma like this: <? php $handle = @fopen("/tmp/inputfile. txt", "r"); if ($handle) { while (($buffer = fgets($handle)) !==

How do I skip the first row in Excel using php?

skip first line or any line in csv file using php we have to add roe number $skip_row_number and pass skip row number in code. so we will check if row meach then skip row.


1 Answers

Oooops. S**t.
I accidently already wrote a function which doesn't strip the spaces:

function str_getcsv2($line, $del=",", $q='"', $esc="\\") {
    $line = rtrim($line, "\r\n");
    preg_match_all("/\G ([^$q$del]*) $del | $q(( [$esc$esc][$q]|[^$q]* )+)$q $del /xms", "$line,", $r);
    foreach ($r[1] as $i=>$v) {  // merge both captures
        if (empty($v) && strlen($r[2][$i])) {
            $r[1][$i] = str_replace("$esc$q", "$q", $r[2][$i]);  // remove escape character
        }
    }
    return($r[1]);
}

Use it like:

$arr = str_getcsv2(fgets($f));
like image 73
mario Avatar answered Oct 23 '22 21:10

mario