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.
Related
I'm not able to read a tabulator seperarated csv file (and yes, i know its csv and no tsv and the c is for tabulator...) with php and seperate it right. When i give out my imported Data with echo or readfile all the tabulators are replaced by a space and i can't use space as a sperator.
Actually i'm a bit confused that this problem is not very common when i use Google, so maybe i'm the problem...
The Problem exists with XAMPP v3.2.3 and PHP Version 7.3.5
$tempFile = fopen($tempFilePath, "r");
$uploadData = fread($tempFile, filesize($tempFilePath));
fclose($tempFile);
echo $uploadData;
$uploadData = str_replace('"','',$uploadData);
$uploadData = str_replace('\r\n','\n',$uploadData);
$uploadData = str_replace('\r','\n',$uploadData);
$uploadData = str_replace(';',',',$uploadData);
$uploadData = str_replace('\t',',',$uploadData); //Here i'm trying to replace the tabulator with a colon to work with it afterwards
When reading a CSV file in PHP, it is best to use the fgetcsv function. With it you can specify the deliminator of the file. The function will output a row of the file. Your deliminator should be "\t".
You should use fgetcsv function which already has functionality to read tsv.
Like this:
$uploadData = [];
if (($handle = fopen("test.csv", "r")) !== false) {
while (($data = fgetcsv($handle, 0, "\t")) !== false) {
$uploadData[] = $data;
}
fclose($handle);
}
If you want to convert tsv to csv you can use inverse function fputcsv:
$fh = fopen('file.csv');
foreach ($uploadData as $datum) {
fputcsv($fh, $datum);
}
fclose($fh);
If you want automatically detect csv delimiter maybe this article can help you.
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
I want to read from a .csv file that is separated by semicolons(;) and text delimiter is double quotes(").
The problem is that the file has 2 fields that contain long HTML data which includes double quotes. When I open it in Excel, it's displayed correctly; however, when using the fgetcsv($file, 0, ";")) function, it gives me a messy data due to the double quotes in the HTML code.
Here's what I tried:
$file = fopen($file, "r");
if ($file) {
while (($row = fgetcsv($file, 0, ";")) !== false) {
if (empty($header)) {
$header = $row;
continue;
}
foreach ($row as $key=>$value) {
$array[$header[$key]] = $value;
}
print_r($array);
}
}
Just a note to those that will suggest me to use strip_tags function: I can't o that as I need the HTML content of the data. Besides, I'm not able to change how the data is put in the CSV, I can just read it.
Can someone helps me in overcoming this issue?
My ideal fix would be a function that can take a CSV file that does not have forced encapsulation (no quotes around values if the value has no spaces or is just a number) and convert it into a CSV file that makes sure every field is encapsulated with double quotes.
<?php
$raw_file = BASE_DIR."pathto/csv.csv";
$fixed_file = BASE_DIR."pathto/fixed.csv";
convert_file($raw_file, $fixed_file);
//move on with life!!
?>
Thanks for you help!
Use fgetcsv to get the contents of your original csv file and fputcsv (using the fourth parameter) to build the encapsulated file.
For example, supposing your column separator is ; :
<?php
$raw_file = BASE_DIR."pathto/csv.csv";
$fixed_file = BASE_DIR."pathto/fixed.csv";
// Getting contents
$raw_handle = fopen($raw_file, 'r');
$contents = array();
while (($data = fgetcsv($raw_handle, 0, ';')) !== false) {
$contents[] = $data;
}
fclose($raw_handle);
// Putting contents
$fixed_handle = fopen($fixed_file, 'w');
foreach ($contents as $line) {
fputcsv($fixed_handle, $line, ';', '"');
}
fclose($fixed_handle);
//move on with life!!
?>
whats wrong with this, when i echo out a row from the csv file and concat anything to the end of the row, it doesnt show up, instead all the rows are echo'ed and the concated string only shows up once at the very end, is this some kind of buffering thing that wont let me concat strings with stuff from my csv file, its running on my local wamp server, and i have tryed different line delimiter in my expload function, im sure the file only uses \n at the end of a line
im trying to parse a csv file row by row so i can check the content of it before i use it to construct an sql statement and insert it into my database.
$file = fopen($filename, "r")
$filesize = filesize($filename);
$filecontent = fread($file, $filesize);
fclose($file);
$rows = explode("\n", trim($filecontent));
foreach ($rows as $row)
{
echo $row . '<br />';
}
You are splitting the string by the string \n. Unless the actual string "\n" appears anywhere in the file, this will probably do nothing. You probably meant "\n" (double quotes), which makes this an actual line break.
Your overall process is terribly inefficient though. You should use fgetcsv and process the file line by line, instead of reading it into memory all at once.
$handle = fopen('test.csv', 'r');
while (($row = fgetcsv($handle)) !== false) {
foreach ($row as $field) {
echo $field . '<br />';
}
}
fclose($handle);
Use fgetcsv() function to convert a CSV file to an array:
$csvFile = "test.csv";
$csvSeparator = ",";
$csvFileLength = filesize($csvFile);
$handle = fopen($csvFile, "r");
$csvData = fgetcsv($handle, $csvFileLength, $csvSeparator);
fclose($handle);
Dump the data to show the structure:
var_dump($csvData);
Now you can convert the data to use in database.