Question

still struggling with PHP and CSV file manipulation. I will try to ask this properly so I can get some help.

I have a CSV file with about 4000 lines/rows, and I wrote this code to create an array of the entire CSV, and pull the the LAST line of the CSV file out to use in my script. The code works to to all this wit success.

// CREATE ASSOCIATIVE ARRAY FROM LAST ROW OF CSV FILE
$csv = array();
if (FALSE !== $handle = fopen("Alabama-TEST.csv", "r"))
{
while (FALSE !== $row = fgetcsv($handle))
{
 $csv[] = $row; 
}
}
$new_csv = array();
foreach ($csv as $row)
{
$new_row = array();
for ($i = 0, $n = count($csv[0]); $i < $n; ++$i)
{
$new_row[$csv[0][$i]] = $row[$i]; 
}
$new_csv[] = $new_row;
}

The variable $new_row is the last row in the CSV and I am able to use the data fine. But when the script is finished running I want to delete this last row called $new_row.

Here is an example of my CSV file at the top view;

CITY        ADDRESS        STATE      NAME
Birmingham  123 Park St.   Alabama    Franky

So I just want to remove the last row and keep the header at the top, for the next time the script runs. I've been trying for 3 days solid trying to figure this out, so I'm hoping some kind person who KNOWS WHAT THEY ARE DOING can help.

Here is the code I have tried to remove the last row;

$inp = file('Alabama-TEST.csv');
$out = fopen('Alabama-TEST.csv','w');
or ($i=0;$i<count($inp)-1;$i++)
fwrite($out,$inp[$i]);
fclose($out);

Since I'm using a large file at around 4000 rows, is there a way to do this without using too much memory?

Was it helpful?

Solution

You need to use array_pop on your array ($new_csv) and fputcsv to save the file:

array_pop($new_csv); // Removes the last element in the array
$out = fopen('Alabama-TEST-new.csv','w');
foreach ($new_csv as $row) { // sorry for writing it badly, try now
 fputcsv($out, $row);
}
fclose($out);

I don't have an environment to test this, sorry.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top