Show CSV rows in reverse order with PHP - php

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);
?>

Related

How to concatenate two columns in a csv file in php?

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

CSV show CRLF at end of each row in MAC but CF in Windows

I am reading content from a csv file with
$row = 1;
if (($handle = fopen($filename, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) { //Reading the file
$num = count($data);
for ($c = 0; $c < $num; $c++) {
$csvData[$row][$c] = $data[$c];
}
$row++;
}
return $csvData;
fclose($handle);
}
but if I create csv on MAC at the end of each row there is CRLF but on windows there is only CR and my script read fine only for windows. How could I fix my script for MAC as well.

write to a csv file

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

php excel to mysql problem

i am trying to build a csv to mysql and i did everything right,
butthe first row of the titles keep entering too, i want it to start from the second row in the csv file,
can you please help me:
$row = 1;
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$userid = mysql_real_escape_string($Sid);
$amount = mysql_real_escape_string($data[0]);
$cardHolderName = mysql_real_escape_string($data[1]);
$cardHolderAddress = mysql_real_escape_string($data[2]);
$cardHolderZipcode = mysql_real_escape_string($data[3]);
$cardHolderCity = mysql_real_escape_string($data[4]);
$cardHolderState = mysql_real_escape_string($data[5]);
$cardHolderCountryCode = mysql_real_escape_string($data[6]);
$cardHolderPhone = mysql_real_escape_string($data[7]);
$cardHolderEmail = mysql_real_escape_string($data[8]);
$cardNumber = mysql_real_escape_string($data[9]);
$cardSecurityCode = mysql_real_escape_string($data[10]);
$cardExpireMonth = mysql_real_escape_string($data[11]);
$cardExpireYear = mysql_real_escape_string($data[12]);
$PurchaseDate = mysql_real_escape_string($data[13]);
$StoreId = mysql_real_escape_string($data[14]);
$ItemCode = mysql_real_escape_string($data[15]);
$ItemName = mysql_real_escape_string($data[16]);
$ItemQuantity = mysql_real_escape_string($data[17]);
$itemShippingType = mysql_real_escape_string($data[18]);
You need to get the first row of data (title row) and "throw it away". Your code example is starting processing without skipping the first row.
if (($handle = fopen($file, "r")) !== FALSE) {
$data = fgetcsv($handle, 1000, ",");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
...
I'm not sure what you're doing with your $row variable, but you could do something like this:
$row = 1;
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($row == 1)
{
$row++;
continue;
}
...

PHP not reading the entire CSV file

I've written a simple bit of code to test two parameters and forward the user to a link.
error_reporting(E_ALL|E_STRICT);
ini_set("display_errors", "On");
$secure_box=$_GET['query'];
$fh = fopen('db.csv', 'r');
$now = date("d.m.Y");
$data=fgetcsv($fh);
$first_name=$data[0];
$date=$data[1];
$url=$data[2];
{
if($secure_box == $first_name AND $date>=$now)
{
header("Location: $url");
exit();
}
else
{
header("Location: http://localhost/x/delivery_method.html");
}
exit;
?>
My problem here is that the entire CSV file is not being read. What can I do ?
The entire file isn't being read because you only called fgetcsv once. fgetcsv only reads one line at a time, you need to put the that code in a loop.
Here is an example of how to use fgetcsv in a loop, from the php docs at http://www.php.net/fgetcsv:
<?php
// Example #1 Read and print the entire contents of a CSV file
$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);
}
?>
This is what I've been able to come up with..Hope it's right
<?php
error_reporting(E_ALL|E_STRICT);
ini_set("display_errors", "On");
$name_value = $_GET['query'];
$fh = fopen('db.csv', 'r');
$now = date("d.m.Y");
$line = 1;
if (($handle = fopen("db.csv", "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$num = count($data);
$line++;
for ($c = 0; $c < $num; $c++)
{
if ($name_value == $data[0] AND $data[1] >= $now)
{
header("Location: $data[2]");
exit();
}
else
{
header("Location: http://localhost/x/client_unauthorized.html");
}
}
}
fclose($handle);
}
?>
You can loop to read the whole file line by line until EOF, and check each row in turn.

Categories