I have a php script running on a regular basis that processes the top 100 rows of a CSV file. When it is done I want it to delete the processed rows from the CSV file.
I
Here is php code for that:
$input = explode("\n", file_get_contents("file.csv"));
foreach ($input as $line) {
// process all lines.
}
// This function removes first 100 elements.
// More info:
// http://php.net/manual/en/function.array-slice.php
$output = array_slice($input, 100);
file_put_contents("out.csv", implode("\n", $output));
Note, if csv file contains header you have to remove first element from array $input
.
I used this script in the passed written by Joby Joseph:
function csv_delete_rows($filename=NULL, $startrow=0, $endrow=0, $inner=true) {
$status = 0;
//check if file exists
if (file_exists($filename)) {
//end execution for invalid startrow or endrow
if ($startrow < 0 || $endrow < 0 || $startrow > 0 && $endrow > 0 && $startrow > $endrow) {
die('Invalid startrow or endrow value');
}
$updatedcsv = array();
$count = 0;
//open file to read contents
$fp = fopen($filename, "r");
//loop to read through csv contents
while ($csvcontents = fgetcsv($fp)) {
$count++;
if ($startrow > 0 && $endrow > 0) {
//delete rows inside startrow and endrow
if ($inner) {
$status = 1;
if ($count >= $startrow && $count <= $endrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
//delete rows outside startrow and endrow
else {
$status = 2;
if ($count < $startrow || $count > $endrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
}
else if ($startrow == 0 && $endrow > 0) {
$status = 3;
if ($count <= $endrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
else if ($endrow == 0 && $startrow > 0) {
$status = 4;
if ($count >= $startrow)
continue;
array_push($updatedcsv, implode(',', $csvcontents));
}
else if ($startrow == 0 && $endrow == 0) {
$status = 5;
} else {
$status = 6;
}
}//end while
if ($status < 5) {
$finalcsvfile = implode("\n", $updatedcsv);
fclose($fp);
$fp = fopen($filename, "w");
fwrite($fp, $finalcsvfile);
}
fclose($fp);
return $status;
} else {
die('File does not exist');
}
}
The function accepts 4 parameters:
filename (string): Path to csv file. Eg: myfile.csv
startRow (int): First row in delete area
endRow (int): Last row in delete area
inner (boolean): decide whether rows deleted are from inner area or outer area
Now Let us consider various cases. I have a csv file with me named ‘test.csv’. Here is the screenshot of the same.
Example 1:
$status = csv_delete_rows('test.csv', 3, 5, true);
will delete the red part of:
Example 2:
$status = csv_delete_rows('test.csv', 3, 5, false);
will delete the red part of:
Example 3: Like in your situation, if you want to delete the first 100 rows, use this:
$status = csv_delete_rows('test.csv', 0, 100);