Saving specific columns of CSV to another CSV file in PHP - php

so trying to read a csv file and extracting details from the file and wish to store specific columns of the csv to another csv file.
I have managed to extract the specific columns of the input csv file but not really sure how I can write those extracted columns to another csv file.
Here is the part of my work:
$row = 1;
if (($handle = fopen("testtable.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
echo $data[0] . "\n" . $data[1] . "<br />\n";
}
$file = fopen("editedTable.csv","w");
foreach ( $data as $line) { //working on this part of the code
fputcsv($file, explode(',',$line));
}
fclose($handle);
}
Obviously there is an error in the foreach loop as I am trying to work out the logic.
The data that is extracted is basically first and the second column (data[0], data[1]). Just need this to write to another CSV file. The input csv is just a comma delimited file with 5 columns. Any idea how I can modify the foreach loop and the use the fputcsv method?
Thanks

fputcsv accepts an array on the second parameter.
I think this is what you looking for:
<?php
$file = fopen("editedTable.csv","w");
$row = 1;
if (($handle = fopen("testtable.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000)) !== FALSE) {
$num = count($data);
$row++;
echo $data[0] . "\n" . $data[1] . "<br />\n";
fputcsv($file, [$data[0], $data[1]]);
}
}
fclose($handle);
fclose($file);

Because you place the fputs outside of the $data initial loop, you catch only one row, here is the modified code.
$row = 1;
$file = fopen("editedTable.csv","w");
if (($handle = fopen("testtable.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
echo $data[0] . "\n" . $data[1] . "<br />\n";
$line = $data[0].", ".$data[1];
$line .= "\n";
fputs($file, $line);
}
fclose($handle);
}
fclose($file);

Related

Edit csv with php

I have csv with about 700 rows. It includes rows like:
92265R-1,1
92526R-3,0
.
.
.
Now my goal is to copy every row to new csv where every row is copied with _x end for 5 times. So final csv would look like this:
92265R-1_1,1
92265R-1_2,1
92265R-1_3,1
92265R-1_4,1
92265R-1_5,1
92526R-3_1,0
92526R-3_2,0
92526R-3_3,0
92526R-3_4,0
92526R-3_5,0
.
.
.
I'm stuck here
Simply try this
$newArray = [];
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
for($i=1 ; $i <=5 ; $i++){
$newArray[] = [
$row[0].'_'.$i,
$row[1]
];
}
}
fclose($handle);
}
$fp = fopen('new.csv', 'w');
foreach ($newArray as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);

Reading CSV file data in PHP

I'm trying to create a page which pulls infoprmation from a CSV file, using PHP.
It should then populate a product list with the information.
This is the CSV file:
The code I have is as follows:
$file = file('data-example.csv');
$line = array("name", "id","price", "description");
foreach($file as $line) {
$csv = explode('//',$line);
$item = $csv;
print_r($item);
This is currently printing out the whole of the array. I'd like to know how I can access the individual nodes on the array, so that I could include them as variables within an HTML table.
Thanks
Ali
To amplify, and respond to the replies (thanks!):
This is the amended code, using fgetcsv:
if (($handle = fopen("data.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
echo($data[1][1]);
}
fclose($handle);
}
This seems to work, but returns the column contents. This is the data (data.csv):
"Dandelion","30","13.99","Dandelion 30 "
"Daisy","40","20.99","Daisy 40 "
"Cress","27","10.99","Cress 27 "
"Coral","17","6.99","Coral 17 ",
"Honeysuckle","40","17.99","Honeysuckle 40 "
"Rose","27","9.99","Rose 27"
"
(there's a new line at dandelion, Daisy,Cress,Coral,Honeysuckle and Rose)
When I try echo($data[1]); it gets the whole column as described, i.e 30 40 27 17 40 27 but echo($data[1][1]); returns "342142", and echo($data[1][1][1]); creates an error.
I don't understand it as this is an array?
Thanks
Ali
You should use native php functions to read csv files, such as str_getcsv
Something like:
$Data = str_getcsv($CsvString, "\n"); //parse the rows
foreach($Data as &$Row){
$Row = str_getcsv($Row, ";"); //parse the items in rows
}
Alternatively you can use fgetcsv that parses the line it reads for fields in CSV format and returns an array containing the fields read, i.e.:
<?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);
}
?>

UPLOAD CSV with special encoding (fgetcsv)

I have the problem with the php function fgetcsv() .
Lets start from the begin . I want to export csv files in ISO encoding and upload csv . With the export csv i dont have problem but with upload csv i have . This code runs perfect when i have not special characters . If i have greek characters he cannot read it and print NULL. If you can find me a solution !!!
Thanks for your time !!!
$csv = array(); $keys = array();
if (($handle = fopen($uploadedcsv, "r")) !== FALSE) {
while (($lines = fgetcsv($handle, 0, $delimiter)) !== FALSE) {
if ($row == 0) {
utf8_encode($keys);
utf8_encode($lines);
mb_convert_encoding($keys,'ISO-8859-15','utf-8');
mb_convert_encoding($lines,'ISO-8859-15','utf-8');
$keys = $lines;
} else {
utf8_encode($keys);
utf8_encode($lines);
mb_convert_encoding($keys,'ISO-8859-15','utf-8');
mb_convert_encoding($lines,'ISO-8859-15','utf-8');
$csv[] = array_combine($keys, $lines);
}
$row++;
}
fclose($handle);`

How to store each row of the csv file to array in php

I have data in csv file as follows.
Mr,Vinay,H S,Application Engineer,vinay.hs#springpeople.com,99005809800,Yes
Mr,Mahammad,Hussain,Application Engineer,vinay.hs#springpeople.com,99005809800,Yes
I want to store each row in each array.explain me how to do that
I did not understand each row in each array.
use fgetcsv() function to read the CSV file php.
An example
<?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);
}
?>
OR
If you want to store them in an array you could use
$data = array();
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while(($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
$data[] = $row;
}
}
Assuming the CSV is a file (if not, make the CSV match the $csv, which is essentially the file broken down in the separate lines), here is a very simple way:
$csv = file('mycsv.csv'); $result = array();
//iterate the lines
foreach ($csv as $line)
// I'd recommend more robust "csv-following" method though (fgetcsv maybe)
$result[] = explode(',',$result);
//show the results
print_r($result);
Though fgetcsv is probably a safer bet (as others have mentioned) (See the docs).
To further extend your comment:
//iterate the lines
foreach ($csv as $line)
// I'd recommend more robust "csv-following" method though (fgetcsv maybe)
$result[] = explode(',',$result);
can become:
//iterate the lines
foreach ($csv as $line)
// combine the current results with the new results
$result = array_marge($result,$line);
or, if order is important:
//iterate the lines
foreach ($csv as $line)
// add each result on to the end of the result array
foreach($line as $val)
// add each value
$result[] = $val;
You can use fgetcsv() for that:
$data = array();
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while(($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
$data[] = $row;
}
}

formatting fgetcsv output

Im trying to figure out how to take the data returned by fgetcsv, and format it into a readable/editable table, and then use fputcsv to save that table
so far i have this
<?php
$row = 1;
$handle = fopen("csv.csv", "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "\n";
}
}
fclose($handle);
?>
The following code will output the CSV in an html table. To make it editable wrap the echo ..$val.. with tags and add a php form handler that takes the result and reforms a CSV
<?php
$row = 1;
$handle = fopen("csv.csv", "r");
echo("<table>");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
echo("<tr>\r\n");
foreach ($data as $index=>$val) {
echo("\t<td>$val</td>\r\n");
}
echo("</tr>\r\n");
}
echo("</table>");
fclose($handle);
?>

Categories