I have a csv file like this:
I would like to concatenate the values of the style_color columns in this csv file. To have for example SCJEG4_1014.
I wrote a script, it creates this last column with the header 'Pictures Names' but in each cell I just have "_".
How can I solve my problem?
<?php
//uploaded xlsx file recovery
$xlsx="C:/wamp64/www/Extract_pictures_Excel/xlsx_files/".date('Y_m_d H-i-s')."_file.xlsx";
move_uploaded_file($_FILES["mon_fichier"]["tmp_name"],$xlsx);
// Excel in CSV
require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$excel = PHPExcel_IOFactory::load($xlsx);
$writer = PHPExcel_IOFactory::createWriter($excel, 'CSV');
$writer->setDelimiter(";");
$writer->setEnclosure("");
$nomcsv = "C:/wamp64/www/Extract_pictures_Excel/csv/".date('Ymd_His').".csv";
$writer->save($nomcsv);
$delimiter = ";";
$csv_data = array();
$row = 1;
if (($handle = fopen($nomcsv, 'r')) !== FALSE) {
while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
$names_pictures = $data[7].'_'.$data[4];
$csv_data[] = $data;
$row++;
}
fclose($handle);
}
$extra_columns = array('Pictures Names' => $names_pictures);
foreach ($csv_data as $i => $data) {
if ($i == 0) {
$csv_data[$i] = array_merge($data, array_keys($extra_columns));
} else {
$csv_data[$i] = $data = array_merge($data, $extra_columns);
}
}
if (($handle = fopen($nomcsv, 'w')) !== FALSE) {
foreach ($csv_data as $data) {
fputcsv($handle, $data, $delimiter);
}
fclose($handle);
}
?>
It looks like you only add in the details from the last row ( as you only use the value of $names_pictures once). It would be better (IMHO) to add this value into the data at the point at which you generate the $csv_data array...
while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
$data['Pictures Names'] = $data[7] . '_' . $data[4];
$csv_data[] = $data;
$row++;
}
You could then remove the foreach ($csv_data as $i => $data) { loop
If you had a different file for the output you could open the output file before the above loop and write the data directly to the output file rather than using $csv_data...
if (($handle = fopen($nomcsv, 'r')) !== FALSE
&& ($ohandle = fopen($nomcsvOutput, 'w')) !== FALSE) {
while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
$data['Pictures Names'] = $data[7] . '_' . $data[4];
fputcsv($ohandle, $data, $delimiter);
}
fclose($handle);
fclose($ohandle);
}
Related
I have a code where a csv file is uploaded ,the data is extracted from it and uploaded to database.Everything works fine,but how can i skip the empty rows and continue reading the rows with data in it.
This is the code where i extract data from csv file
if (($source = fopen( $csv_file, "r")) !== FALSE)
{
//read data from excel
while (($data = fgetcsv($source, 1000, ",")) !== FALSE)
{
$question=$data[0];
$point=$data[1];
$header=$data[2];
$footer=$data[3];
$type_value=$data[4];
$group_name=$data[5];
echo $question;
}// while end
}
If you use PHP's SplFileObject instead of the basic fgetcsv() function, it has built-in options to skip empty lines:
$file = new SplFileObject($csv_file);
$file->setFlags(SplFileObject::READ_CSV SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE);
foreach ($file as $data) {
...
}
if ($data[0] == NULL)
continue;
This is because fgetcsv returns a non-empty array with a null element inside.
Try it with
if ($data === null) continue;
I didn't test it, but I sthink it should work.
Try this
if (($source = fopen( $csv_file, "r")) !== FALSE)
{
// read data from excel
while (($data = fgetcsv($source, 1000, ",")) !== FALSE)
{
if ((string) $data[0] != '0' and empty($data[0]))
{
continue;
}
$question = $data[0];
$point = $data[1];
$header = $data[2];
$footer = $data[3];
$type_value = $data[4];
$group_name = $data[5];
echo $question;
}
}
I have a CSV file loaded from an URL, and I want to loop over the lines with PHP.
Here is a typical line of this CSV:
1004000018;active;"TEST1";"TEST2";"TEST3";"TEST4"
I would like to get this result, for each row:
1004000018
active
TEST1
TEST2
TEST3
TEST4
You can achieve this using the php function fgetcsv, this should work :
PHP
$file = fopen('file.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
//$line[0] = '1004000018' in first iteration
print_r($line);
}
fclose($file);
This will help you for read csv:
if (($handle = fopen("$source_file", "r")) !== FALSE) {
$columns = fgetcsv($handle, $max_line_length, $delemietr);
if (!$columns) {
$error['message'] = 'Empty';
return ($error);
}
while (($rows = fgetcsv($handle, 10000, "\t")) !== false) {
if ($rows[1] && array(null) !== $rows) { // ignore blank lines
$data1 = $rows[1];
}
}
}
Trying to get this code to echo the rows it gets from the CSV file in reverse order. Any idea how to do this?
<?php
$row = 1;
$FILE = "file.csv";
if (($handle = fopen($FILE, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
if ($c == 0) $first = $data[$c];
if ($c == 1) $second = $data[$c];
}
}
fclose($handle);
}
?>
Create a specific function for this task and call the function. It is always easier to split your program into smaller pieces. You need to read the data into an array and the reverse the order.
<?php
function loadCSV($file) {
$rows = array();
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
array_push($rows, $data);
}
fclose($handle);
}
return array_reverse($rows);
}
?>
Here is how to use this function:
<?php
$data = loadCSV('data.csv');
print_r($data);
?>
getHistory downloads a CSV file from Yahoo finance API, i am trying to get the CSV file, and insert the symbol infront of each of the entries in the file. After that is done i want to write the CSV file back to $symbol.csv. My data is the way i want it, i just cant seem to write it to a CSV file. What am i doing wrong? Or is there a better way to go about this?
$row = 1;
if (($handle = fopen(getHistory("T","2010-06-1"), "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
if($row = 1){array_unshift($data,"Symbol"); }
else { array_unshift($data, "T"); }
$fp = fopen('t.csv', 'w');
fputcsv($fp, $data);
fclose($fp);
$row++;
}
}
fclose($handle);
In your loop, you are opening and closing the file on each iteration. You should open the csv file before the loop, add to it, then close it when the loop is done.
Also, you should use === or == for comparisons.
$row = 1;
if (($handle = fopen(getHistory("T","2010-06-1"), "r")) !== FALSE) {
// This truncates the file to zero length
// so, we only need to do this once, before the loop
$fp = fopen('t.csv', 'w');
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
if($row === 1){array_unshift($data,"Symbol"); }
else { array_unshift($data, "T"); }
fputcsv($fp, $data);
$row++;
}
// Close it once we're all done
fclose($fp);
}
fclose($handle);
I have .csv file with 4 columns. What's the easiest way to remove a line identical with the id of the first column? Here's where I got stuck:
if($_GET['id']) {
$id = $_GET['id'];
$file_handle = fopen("testimonials.csv", "rw");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
if ($id == $line_of_text[0]) {
// remove row
}
}
fclose($file_handle);
}
Unfortunately, databases were not a choice.
$table = fopen('table.csv','r');
$temp_table = fopen('table_temp.csv','w');
$id = 'something' // the name of the column you're looking for
while (($data = fgetcsv($table, 1000)) !== FALSE){
if(reset($data) == $id){ // this is if you need the first column in a row
continue;
}
fputcsv($temp_table,$data);
}
fclose($table);
fclose($temp_table);
rename('table_temp.csv','table.csv');
I recently did a similar thing in for a newsletter unsubscription, heres my code:
$signupsFile = 'newsletters/signups.csv';
$signupsTempFile = 'newsletters/signups_temp.csv';
$GLOBALS["signupsFile"] = $signupsFile;
$GLOBALS["signupsTempFile"] = $signupsTempFile;
function removeEmail($email){
$removed = false;
$fptemp = fopen($GLOBALS["signupsTempFile"], "a+");
if (($handle = fopen($GLOBALS["signupsFile"], "r")) !== FALSE) {
while (($data = fgetcsv($handle)) !== FALSE) {
if ($email != $data[0] ){
$list = array($data);
fputcsv($fptemp, $list);
$removed = true;
}
}
fclose($handle);
fclose($fptemp);
unlink($GLOBALS["signupsFile"]);
rename($GLOBALS["signupsTempFile"], $GLOBALS["signupsFile"]);
return $removed;
}
this uses the temp file method of writing out the csv line by line to avoid memory errors. Then once the new file has been created, it deletes the original and renames the temp file.
You can modify this code so that it looks for an ID instead of an email address eg:
$id = $_GET['id'];
$fptemp = fopen('testimonials-temp.csv', "a+");
if (($handle = fopen('testimonials.csv', "r")) !== FALSE) {
while (($id= fgetcsv($handle)) !== FALSE) {
if ($id != $data[0] ){
$list = array($data);
fputcsv($fptemp, $list);
}
}
fclose($handle);
fclose($fptemp);
unlink('testimonials.csv');
rename('testimonials-temp.csv','testimonials.csv');
$id = $_GET['id'];
if($id) {
$file_handle = fopen("testimonials.csv", "w+");
$myCsv = array();
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
if ($id != $line_of_text[0]) {
fputcsv($file_handle, $line_of_text);
}
}
fclose($file_handle);
}
You can do:
$new = '';
while (!feof($file_handle))
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($id != $line_of_text[0])
{
$new .= implode(',',$line_of_text) . PHP_EOL;
}
}
basically you running threw each line and check if the id does NOT match the id sent in the get parameter, if it does not then it writes the line to the new container / variable.
And then rewrite the $new value to the file, this should work ok:
How big is the file
Do you have a CSV Header on line 0?
I have found a solution, that does not need to copy the file.
$file = 'testimonials.csv'
// open two handles on the same file
$input = fopen($file ,'r'); // read mode
$output = fopen($file, 'c'); // write mode
if($input !== FALSE && $output !== FALSE) { // check for error
while (($data = fgetcsv($input, $CSVLIMIT, $sep)) !== FALSE) {
if(reset(data) == $id) {
continue;
}
fputcsv($output, $data, $sep);
}
// close read handle
fclose($input);
// shorten file to remove overhead created by this procedure
ftruncate($output, ftell($output));
fclose($output);
}
Note: only one of those fopen commands could fail, leaking the handle for the second one. It would be good, to check both handles independetly and close them on a error.