I am trying to import csv. And, here is my csv file for test.
https://drive.google.com/file/d/1LU4SHG_EbSj9OTRXRakNHgllZD45iaS3/view?usp=sharing
I am providing exact file so that the file structure / encoding may not changed if I paste the csv text here.
I am using CSV League https://csv.thephpleague.com/ and I have code for import as follows:
$header_row = 0;
$filename = 'test_extra.csv'
$csv_file_path = storage_path('app/files/').$filename;
if (!ini_get("auto_detect_line_endings")) {
ini_set("auto_detect_line_endings", TRUE);
}
$csv = Reader::createFromPath($csv_file_path, 'r');
//trying to conver encode to utf-8
$csv->addStreamFilter('convert.iconv.ISO-8859-15/UTF-8');
$csv->setHeaderOffset($header_row);
$sample_data = $csv->fetchOne($header_row);
print_r($sample_data);
But, It is printing data as:
This is totally weird because the first row possess data something like:
0858,0858-A1,One Bedroom All.a1,1,1,702,2,1X1,0
Is there something I might be missing?
Related
I have a csv file that have data like this:
Sub District District
A Hi อาฮี Tha Li District ท่าลี่
A Phon อาโพน Buachet District บัวเชด
when I tried to read it using php code by following this SO question:
<?php
//set internal encoding to utf8
mb_internal_encoding('utf8');
$fileContent = file_get_contents('thai_unicode.csv');
//convert content from unicode to utf
$fileContentUtf = mb_convert_encoding($fileContent, 'utf8', 'unicode');
echo "parse utf8 string:\n";
var_dump(str_getcsv($fileContentUtf, ';'));
But it didn't work at all. Someone please let me know what I am doing wrong here.
Thanks in advance.
There are 2 issues with your code:
Your code applies str_getcsv to whole file contents (instead of individual line)
Your code example is using delimiter ";" but there is no such symbol in your input file.
Your data is in either fixed field length format (which is actually not a csv file) or in tab delimited csv file format.
If it is tab delimited file format then you can use 2 ways to read your file:
$lines = file('thai_unicode.csv');
foreach($lines as $line){
$data = str_getcsv($line,"\t");
echo "sub_district: ". $data[0].", district: ".$data[1]."\n";
}
or
$f = fopen('thai_unicode.csv',"r");
while($data = fgetcsv($f,0,"\t")){
echo "sub_district: ". $data[0].", district: ".$data[1]."\n";
}
fclose($f);
And in case you have fixed length fields data format you need to split each line yourself because csv related php function are not suitable for this purpose.
So you will end up with something like this:
$f = fopen('thai_unicode.csv',"r");
while($line = fgets($f)){
$sub_district = mb_substr($line,0,20);
$district = mb_substr($line,20);
echo "sub_district: $sub_district, district: $district\n";
}
fclose($f);
I want to be able to read a csv file, decode it with PHP base64_decode() and then write that decoded data to a new file in the same format.
I tried reading the file line by line and then decoding it while it read the file but the data kept coming out corrupt or broken (containing symbols and random characters).
My csv file has only one column of base64 encoded strings with no delimiters. Each string is on its own row and there is only one string per row.
Like so:
ZXhhbXBsZUBlbWFpbC5jb20=
ZXhhbXBsZUBlbWFpbC5jb20=
ZXhhbXBsZUBlbWFpbC5jb20=
ZXhhbXBsZUBlbWFpbC5jb20=
etc...
I want my new file to be in the same format and the same data but it should be decoded.
like so:
example#email.com
example#email.com
example#email.com
example#email.com
etc...
This is how I am reading the data. I tried using trim() inside base64_decode to get rid of any possible white space or characters but it didn't help. I haven't got to the write to csv part yet because I need proper output.
// csv file is uploaded via a form, I move it to the uploads/ directory
$csv_file = $_FILES['file']['name'];
// filename will always be the user uploaded file
$file_name = $csv_file;
// open the file in read
if (($handle = fopen("uploads/".$file_name, "r")) !== FALSE) {
// read the file line by line
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
// display column of data
echo base64_decode($data[0]);
}
// close file
fclose($handle);
}
My expected output:
example#email.com
example#email.com
example#email.com
example#email.com
etc...
My actual output:
�XZ�˘��A͡����չ兡��������X\�\�[�\�PXZ�˘��\�\��YM�XZ�˘��G7FWfV�g&GF������6��email#example.com�]�[�ܙ[�XZ�˘��G6ӓ���#T�����6��#7C7##4�����6��ɽ���Ѽ��������兡��������ٜ̌LPXZ�˘��Aɕ�����������email#examplevV�W'6��CCT�����6��v�G7W���d�����6��v���v��&W$�����6��ݥ�����齝兡������wwwemail#exampleemail#exampleۙ�\�MLMP[����]]��NNۚ�XZ�˘��Aщɽݸ������兡������[٘[M�[����Aѡ������͕�٥���
�������ѡ����ѽ�������������[YX���ܝ
Got it working...just needed to auto-detect line endings.
// without this my code breaks, I'm assuming since my csv has no delimiter it was having issues finding the line endings
ini_set('auto_detect_line_endings', TRUE);
// Store each row in this array
$allRowsAsArray = array();
// open file
if (!$fp=fopen("uploads/".$csv_file,"r")) echo "The file could not be opened.<br/>";
// add each row from col into array
while (( $data = fgetcsv ( $fp , 0)) !== FALSE )
{
$allRowsAsArray[] = $data;
}
// decode array line by line, also add linebreaks back in
foreach($allRowsAsArray as $result) {
echo base64_decode($result[0])."\n";
}
<?php
$file = new SplFileObject("data.csv");
while (!$file->eof()) {
echo base64_decode($file->fgetcsv());
}
I have a working system on which I get the data of two .csv file. And save all the data into array and then compare some of the data existing on both csv file. The system works well but later I found out that some of the rows doesn't display on the array. I think I don't use the proper code in reading a csv file. I want to edit/improve the system. This is my code on reading or getting the data from csv file.
$thedata = array();
$data = file("upload/payment.csv");
foreach ($data as $deposit){
$depositarray = explode(",", $deposit);
$depositlist = $depositarray;
$key = md5($depositlist[9] . $depositlist[10]);
$thedata[$key]['payment'] = array(
'name' => $depositlist[0],
'email' => $depositlist[1],
'modeofpayment' =>$depositlist[8],
'depositdate' => $depositlist[9],
'depositamount' => number_format($depositlist[10],2)
);
}
'<pre>',print_r($thedata),'</pre>';
//more code here for comaparing of datas...
1.) What is wrong with file("upload/payment.csv") when reading csv file?
2.) What is the best code in reading a csv file that is applicable on the
system, not changing the whole code. Should remain the foreach loop.
3.) Is fgetcsv much better for the existing code? What changes should be made?
Yes, You can use "fgetcsv" for this purpose.
The fgetcsv() function parses a line from an open file.This function returns the CSV fields in an array on success, or FALSE on failure and EOF.
check the examples given below
eg1 :
<?php
$file = fopen("contacts.csv","r");
print_r(fgetcsv($file));
fclose($file);
?>
eg 2:
<?php
$file = fopen("contacts.csv","r");
while(! feof($file))
{
print_r(fgetcsv($file));
}
fclose($file);
?>
Link : https://gist.github.com/jaywilliams/385876
I need to import csv file with php getcsv function but the file is not well formated and cannot import it. After uploading the file, I'd like to delete all " inside the file to have a proper file with ; for each field.
This is an example of my file:
"DENO;NAME;SURNAME;""BIRTH"";""ZIP"";CITY;E-MAIL;TELEPHONE"
"M;DAVID;BON;""1959-02-12 00:00:00"";75009;PARIS;email#gmail.com;010000000"
"M;DOE;JHON;""1947-02-02 00:00:00"";75008;PARIS;email#gmail.com;060000000"
"M;DAVE;Philippe;""1950-01-01 00:00:00"";75002;""PARIS"";email#gmail.com;070000000"
I think I would need to read each line of the file,and maybe use str_replace but I don't know how to write the new file...
Assuming you can get your code into a text string, you can just replace/remove the double-quotes. Then parse the text and get it into a format that will support fputcsv().
When writing the folder, be sure to check that your user has permissions to write to this folder (for example if the parent folder has permissions drwxr-xr-x, you can fix it with chmod g+w folder_name).
<?php
// sample text to parse
$some_text = '"DENO;NAME;SURNAME;""BIRTH"";""ZIP"";CITY;E-MAIL;TELEPHONE"
"M;DAVID;BON;""1959-02-12 00:00:00"";75009;PARIS;email#gmail.com;010000000"
"M;DOE;JHON;""1947-02-02 00:00:00"";75008;PARIS;email#gmail.com;060000000"
"M;DAVE;Philippe;""1950-01-01 00:00:00"";75002;""PARIS"";email#gmail.com;070000000"';
// remove quotes
$final_text = str_replace('"', '', $some_text);
// create array of rows by searching for new lines
$data = str_getcsv($final_text, "\n");
// create an empty array to save our final csv data
$final_csv = array();
// loop thru the array and save to the final csv data
foreach ($data as $value) {
// before saving to final csv data, split row into individual column items
$value_array = explode(";", $value);
$final_csv[] = $value_array;
}
// helper debugger to show data before writing it
echo "<pre>";
print_r($final_csv);
echo "</pre>";
// create a new file for writing or open and truncate to 0
$fp = fopen('file.csv', 'w');
// write to file from final csv data
foreach ($final_csv as $fields) {
fputcsv($fp, $fields);
}
// close file
fclose($fp);
?>
I have parsed a page with a table and I have an array with data. I need to export this data to CSV file, but want to save formating, especially superscipt. Here is my code:
$filename = 'data.csv';
$arraySup['data1'] = 'Value1';
$arraySup['data2'] = 'Value2';
$arraySup['data3'] = '<div><b>6</b><sup>3</sup></div>';
$arraySup['data4'] = '<div><b>2</b><sup>1 1/2</sup><br>49.67</div>';
$handle = fopen($filename, 'a+');
fputcsv($handle, $arraySup);
fclose($handle);
I need to get this on output in my CSV file.
Here is link to image what I want to get.
https://www.dropbox.com/s/94yfxrveug5uce4/superscript_example.png?dl=0
I will appreciate any help in this question.