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
The fgetcsv() function parses a line from an open file, checking for CSV fields.
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.
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)) !==
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With