PHP fgetcsv(): delimiter must be a single character - php

I have the following code, that I use to read a csv file with CRLF as lines endings
if (($fp = fopen($path, "r")) !== FALSE) {
while (($record = fgetcsv($fp, 1000, "\r\n")) !== FALSE) {
if ($row == 0) {
$record[0] = $batchHeader;
}
$newCsvData[] = $record;
$row++;
}
}
When I upload the csv file I get the following error: fgetcsv(): delimiter must be a single character
Here is a sample or my csv:
Thanks.

I'm guessing it reads "\r\n" as your delimiter. Have you tried fgetcsv($fp, 1000, "|") ?
It should auto-detect line endings.
PHP reference

The parameter in question is the delimiter (field separator), not the row separator. In your case, |should be your delimiter. The function will handle line endings itself.
Take a read for more information at http://php.net/manual/en/function.fgetcsv.php

Related

PHP read CSV file till tab space

I have a CSV file whose contents are as below.
1 2 3 4 \t 45 56 67
As seen above, after the value 4, I have a tab space. I need to read the values only till tab space. I am able to open the CSV file and read till tab delimiter as below.
$file = fopen("outputfile.csv","r");
//I am reading till tab space.
while ($line = fgetcsv($file, 0, "\t") !== false)
However, now I need to read all the values till tab space into PHP array for some manipulation. How can I achieve the same?
Try:
while ($line = fgetcsv($file, 0, "\t") !== false) {
$columns = str_getcsv($line, ' '); //or use explode()
}
explode() is the way to go.
$file = fopen("outputfile.csv","r");
while ($line = fgetcsv($file, 0, "\t") !== false)
{
$array = explode(' ', $line);
}
I would split the line into "before tab" and "after tab" components, and only do the parsing on the "before tab" half:
$file = fopen("outputfile.csv","r");
// for each line in the file, until EOF
while( ($line = fgets($file)) !== false) {
// split out the tab char:
$beforeTab = explode( "\t", $line)[0];
// now, parse the CSV part
$parsedCSV = str_getcsv( $beforeTab);
// do what you need with the parsedCSV array.
}

PHP str_replace CSV Content

I am getting the contents of a CSV file and displaying (it works).
if (($handle = fopen($url, 'r')) === false) {
die('Error opening file');
}
$headers = fgetcsv($handle, 1024, ',');
$complete = array();
while ($row = fgetcsv($handle, 1024, ',')) {
$complete[] = array_combine($headers, $row);
}
fclose($handle);
However, in this CSV file there is a field that has contents for example like this:
"123456,123456,123456,123456"
I think my code isn't processing because of the double quotes, I think I need to convert to single quotes. If thats the case how would I integrate the following (I was thinking something like):
str_replace('"',"'", $url);
Look at the other parameters for fgetcsv()
By default the enclosure character is set to ", which means anything between quotes should be considered a single value. Replace that parameter with what you actually use as the enclosure character in the csv and it will work.
Something like (if your enclosure character is '):
while ($row = fgetcsv($handle, 1024, ',', "'")) {
Better than to read it wrong and try to fix it afterwards with str_replace.

Converting CSV to PHP Array - issue with end line (CR LF)

I am converting csv file to an array using code bellow. But, problem is that end of the row is CR LF, and it is not detected, so array has wrong offset. CR LF is ignored and "cells" around it are merged.
How could i rewrite code to detect this row ending and split array correctly ? Or, is there better approach to convert csv to array?
There are some simmilar questions here but i have not found solution to this issue yet.
Thanks.
$fileName ='test.csv';
$csvData = file_get_contents($fileName);
$csvNumColumns = 11;
$csvDelim = ";";
$data = array_chunk(str_getcsv($csvData, $csvDelim), $csvNumColumns);
print_r($data);
Have you tried using fgetcsv()? full info on php.net.
Example usage from php.net
<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>
I would avoid str_getcsv() and work with fgetcsv() to avoid dealing with some of the end of line futz.
http://php.net/manual/en/function.fgetcsv.php
if (($handle = fopen("fileName", "r")) !== FALSE) {
while (($data = fgetcsv($handle)) !== FALSE) {
var_dump($data); //array representation of one line of csv...
}
}
fclose($handle);
If you're on a Mac...
Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

CSV file read fail (PHP )

I am trying to read a CSV file (delimited by commas) but unfortunately, it isn't responding as it ought to. I am not so sure what I am doing wrong here, but I'll paste out the contents of the code and the CSV file both :
$row = 0;
if($handle = fopen("SampleQuizData.csv","r") !== FALSE)
{
// WORKS UNTIL HERE, SO FILE IS BEING READ
while(!feof(handle))
{
$line = fgetcsv($handle, 1024, ",") ;
echo $line[2]; // DOES NOT WORK
}
}
Here is the CSV file: (the emails and names have been changed here to protect the identities of the users)
parijat,something,parijatYkalia#hotmail.com
matthew,durp, mdurpdurp#gmail.com
steve,vai,stevevai#gmail.com
rajni,kanth,rajnikanth#superman.com
it lacks a '$' to the handle variable
while(!feof($handle)){
and not :
while(!feof(handle)){
Give this a try:
<?php
$row = 0;
if (($handle = fopen("SampleQuizData.csv", "r")) !== FALSE)
{
while(!feof($handle))
{
$line = fgetcsv($handle, 1024, ",") ;
echo "$line[2]";
}
}
?>
It's worth a mention but when I was working on CSV exports a few weeks ago, I had weird line ending inconsistencies. So I put this at the top of my php file and it worked splendid.
<?php
ini_set("auto_detect_line_endings", true);
?>

Some characters in CSV file are not read during PHP fgetcsv()

I am reading a CSV file with php. Many of the rows have a "check mark" which is really the square root symbol: √ and the php code is just skipping over this character every time it is encountered.
Here is my code (printing to the browser window in "CSV style" format so I can check that the lines break at the right place:
$file = fopen($uploadfile, 'r');
while (($line = fgetcsv($file)) !== FALSE) {
foreach ($line as $key => $value) {
if ($value) {
echo $value.",";
}
}
echo "<br />";
}
fclose($file);
As an interim solution, I am just finding and replacing the checkmarks with 1's manually, in Excel. Obviously I'd like a more efficient solution :) Thanks for the help!
fgetcsv() only works on standard ASCII characters; so it's probably "correct" in skipping your square root symbols. However, rather than replacing the checkmarks manually, you could read the file into a string, do a str_replace() on those characters, and then parse it using fgetcsv(). You can turn a string into a file pointer (for fgetcsv) thusly:
$fp = fopen('php://memory', 'rw');
fwrite($fp, (string)$string);
rewind($fp);
while (($line = fgetcsv($fp)) !== FALSE)
...
I had a similar problem with accented first characters of strings. I eventually gave up on fgetscv and did the following, using fgets() and explode() instead (I'm guessing your csv is comma separated):
$file = fopen($uploadfile, 'r');
while (($the_line = fgets($file)) !== FALSE) // <-- fgets
{
$line = explode(',', $the_line); // <-- explode
foreach ($line as $key => $value)
{
if ($value)
{
echo $value.",";
}
}
echo "<br />";
}
fclose($file);
You should setlocale ar written in documentation
Note:
Locale setting is taken into account by this function. If LANG is e.g. en_US.UTF-8, files in one-byte encoding are read wrong by this function.
before fgetcsv add setlocale(LC_ALL, 'en_US.UTF-8'). In my case it was 'lt_LT.UTF-8'.
This behaviour is reported as a php bug

Categories