I'm trying to count the columns of the first .csv file line.
This is my file content (CRLF -> carriage return and linefeed): test.csv
A;B;C;crlf
Script:
$handle = fopen($filePath,'r');
$data = fgetcsv($handle, 1000, ";");
print_r($data) . PHP_EOL;
echo 'column nr.: ' . count($data) . PHP_EOL;
Output:
Array
(
[0] => A
[1] => B
[2] => C
[3] =>
)
column nr.: 4
Why does the function includes the blank column if the line ends after the last ; I expect to count only 3 columns not 4.
Thanks
I'm omiting the last semicolon with the following method: Ok, the CSV now has 25 columns each line and is created with the following method:
public function createRowForFile(Array $content, $fileName, $sep, $carriageReturnLineFeed) {
$contentRow = '';
$noSep = '';
$lastColumn = count($content);
$columnNr = 1;
foreach ($content as $contentName => $contentValue) {
// the semicolon after the last column is omited, because semicolonsdefine breaks between columns,
// (
// ex: A;B;C; columns nr = 4 WRONG
// A;B;C columns nr = 3 OK
// )
if ($lastColumn === $columnNr) {
$sep = $noSep;
}
$columnNr++;
$contentRow.= $contentValue . $sep;
}
$contentRow.= $carriageReturnLineFeed;
$this->writeFileInDir($fileName, $contentRow);
}
Any suggestion?
;at the end of the line. The line endings are not actually the issue. Your line should beA;B;C\r\n.fputcsv().