PHP and CSV file - how to detect end of line? [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to extract data from csv file in php
I have some data in XLS, I save them as CSV, the delimiter is **comma*.
Then I am trying to load the data from this CSV file:
$input = explode("\r\n", fread($file, filesize("my_data.csv")));
print_r($input);
The output:
Array ( [0] => data from the CSV file)
This is the problem - in the array is always just one item, where are printed out all data from the CSV file. How is that possible? Why isn't in the array as much items as is rows in the CSV file?
Also, I've tried to change "\r\n" for "\n", but it's the same.
What I am trying to do - load each line from the CSV file and this each line to process.
EXAMPLE OF THE FILE:
a,b,c,d
e,f,g,h
OUTPUT:
a,b,c,d e,f,g,h

I'd recommend using php's built in csv file reading function fgetcsv() and not create your own: http://php.net/manual/en/function.fgetcsv.php
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$row = implode (",",$data); //puts back together the row from the csv
echo $row. "\n"; //assuming you want a visual linebreak on console, add the \n
}
fclose($handle);
}

How I solved this issue:
In the XLS file, before exporting the file into CSV, I added in the end of sheet one more column with the char '.

Related

How do I open a csv file, read the file line by line, base64_decode() it and write the decoded data to a new file?

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());
}

How to read .csv file row wise using PHP

I am trying to make a PHP script that reads each row of a .csv file. I want to treat each row as an array of data. Please suggest how I can achieve the above?
Use the function fgetcsv().
// Read the first line, headers
$headers = fgetcsv($file);
// Now $headers is an array of your headers
// Read the lines one by one
while (false != ($line = fgetcsv($file))) {
// $line is an array of your cells
}
You could use the following to create an array from the csv;
$aArray = str_getcsv ( file_get_contents("/path/to/file.csv") , ',', '"', "\\");
var_dump($aArray);
Have a read of the PHP manual;
str_getcsv() and file_get_contents()
You can use following to read row from csv file and create array from the csv file:
<?php
$file = fopen("/path/to/file.csv","r");
$arrayCsv = array();
while(!feof($file)) {
$fpTotal = fgetcsv($file);
array_push($arrayCsv,$fpTotal);
}
fclose($file);
print_r($arrayCsv); //prints array from csv
?>
You can use the fgetcsv function to read data from a csv file. Please, look at this :
http://php.net/manual/en/function.fgetcsv.php

PHP fgetcsv 2 dimensional array

I have seen few similar examples but it is still not working.
csv data file "data1.csv" is as below:
symbol,num1,num2
QCOM,10,100
QCOM,20,200
QCOM,30,300
QCOM,40,400
CTSH,10,111
CTSH,20,222
CTSH,30,333
CTSH,40,444
AAPL,10,11
AAPL,20,22
AAPL,30,33
AAPL,40,44
--end of file ----
$inputsymbol = QCOM ; // $inputsymbol will come from html.works fine.
I want to read the csv file and fetch lines that matches symbol = QCOM. and convert it in to array $data1 to plot line chart for num1 and num2 as below.
$data1 = array (
array(10,100),
array(20,200),
array(30,300),
array(40,400)
);
Note: 1. no comma at the end of each csv lines in csv datafile.
2. Multiple symbols in same file. so the lines that match symbols only
should be included in $data1.
==============
Mark's soluition solves the problem. Now to make the data access faster (for a very large csv file), I have (externally) formatted same data as below. Question is how it can automatically extract headers and then for the data1 array?
symbol,1/1/2015,1/2/2015,1/3/2015,1/4/2015
QCOM,100,200,300,400
CTSH,11,22,33,44
AAPL,10,11,12,13
Note that the number of fields in header is not fixed. (it will increase every month). But the data will also increse accordingly.
Not complicated:
$inputsymbol = 'QCOM';
$data1 = [];
$fh = fopen("data1.csv", "r"));
while (($data = fgetcsv($fh, 1024)) !== FALSE) {
if ($data[0] == $inputsymbol) {
unset($data[0]);
$data1[] = $data;
}
}
fclose($fh);
So where exactly are you having the problem?

Converting CSV Array

I am trying to convert a CSV file into a PHP array, somehow it joined all the things in a single string. I wish to start a new line with the * sign,end with the ",," and separate by using ",".
Here are parts of the csv:
*,Alerts,Alert,Type,Text,,,,,,phr_ccr,alert,Type,,
*,Alerts,Alert,Type,Code,Value,,,,,phr_ccr,alert,Type,,
*,Alerts,Alert,Type,Code,CodingSystem,,Text,,,phr_ccr,alert,Type,,
*,Alerts,Alert,Agent,Products,Product,Description,Code,Value,,phr_ccr,alert,Product_Name_CD,,
*,Alerts,Alert,Agent,Products,Product,Description,Code,CodingSystem,,phr_ccr,alert,Product_Name_CDS,,
*,Alerts,Alert,Agent,Products,Product,Description,ProductName,*,,phr_ccr,alert,Product_Name,,
Try this code if it helps:
$csv_name;#name of ur csv file
$raw_data=array();
$count=0;
$csv = fopen($csv_name[$count_list], 'r');
while (($csv_data = fgetcsv($csv, ",")) !== FALSE)
{
#your csv column names:
$alert=$csv_data[0];
$alerttype=$csv_data[1];
#and so on
$raw_data[$count]=$alert."#".$alerttype."#so on according to ur need";
$count++;
}

inserting csv file data into an array (PHP)

I am attempting to insert the data from an uploaded file into a single dimension array.
The file is as such that there is one student number to a line like so:
392232,392231,etc
this is the most common way I've found online:
while (($line = fgetcsv($file, 25, ',')) !== FALSE) {
//$line is an array of the csv elements
print_r($line);
}
However form what I understand this will create an array ($line) for each row. Which is not what I want.
that aside I tried this to see if it is working and my code is not printing out the array after using ftgetcsv(). The file is successfully uploading.
here is my code:
if(isset($_FILES['csv_file']) && is_uploaded_file($_FILES['csv_file']['tmp_name'])){
//create file name
$file_path = "csv_files/" . $_FILES['csv_file']['name'];
//move uploaded file to upload dir
if (!move_uploaded_file($_FILES['csv_file']['tmp_name'], $file_path)) {
//error moving upload file
echo "Error moving uploaded file";
}
print_r($_FILES['csv_file']);
$file = fopen('$file_path', 'r');
while (($line = fgetcsv($file, 25, ',')) !== FALSE) {
//$line is an array of the csv elements
print_r($line);
}
//delete csv file
unlink($file_path);
}
First off, can anyone obviously see why it wouldnt work to at least print them as seperate arrays of data (each row).
Second, is it possible to set it so that it creates a 1d array of all rows in the file?
Many thanks,
Question 1 is because of
print_r($_FILES['csv_file']);
$file = fopen('$file_path', 'r');
should be:
$file = fopen($file_path, 'r');
and for Question 2, check out the array_push
1st Question:
This line will actually try to open a file called '$file_path' because you're using single quotes (so it doesn't expand to the value of the variable). You can just remove the quotes.
$file = fopen('$file_path', 'r');
$file is null after this.
2nd Question:
If all you want to do is convert a file into an array by lines you can use one of these instead:
file() - get whole file into a 1D array of lines of the file (closest to what you want)
fgets() - get a string per line per call; keep calling this until it returns false to get each line one at a time
file_get_contents() - get the whole file into a string and process as you like
According to PHP.net $line has to return as array.
"returns an array containing the fields read."
But if you are sure it's contains only one student number you can use $line[0] to get the first line value (Ignoring the ",")
Here are some general comments on your code:
You are passing the file path into the fopen() function incorrectly. The variable should not be surrounded with single quotes.
Since you are deleting the CSV file after processing it, moving it is unnecessary. Simply use $_FILES['csv_file']['tmp_name'] as the path to the file.
Since there is only one entry per row in your CSV file, simply access the first element of the array that is returned from fgetcsv(): $numbers[] = $line[0];

Categories