Ahmar Ali
Ahmar Ali

Reputation: 1068

Remove first line in CSV and then save the file overwriting existing

I have a CSV file which is generated dynamically. I want to remove the first line of CSV and then save it again.

I have googled and was able to get first line of csv but the part of writing it again after removing is where I am stuck.

Here is example

line1,data1
line2,data2
line3,data3

What I want to acheive

line2,data2
line3,data3

That is first line removed and file saved again

Here is my code

$file = fopen('words.csv', 'r');
$data = fgetcsv($file,10000,",");
$data = array_shift($data);
$file = fopen('words.csv', 'w');
fputcsv($file,$data,",");
fclose($file);

I get this: ! ) Warning: fputcsv() expects parameter 2 to be array, string given in C:\wamp\www\scrape\test.php on line 7

And output file is empty.

Ahmar

Upvotes: 5

Views: 10213

Answers (2)

Qarib Haider
Qarib Haider

Reputation: 4906

// Read the file
$file = fopen('words.csv', 'r');

// Iterate over it to get every line 
while (($line = fgetcsv($file)) !== FALSE) {
  // Store every line in an array
  $data[] = $line;
}
fclose($file);

// Remove the first element from the stored array / first line of file being read
array_shift($data);

// Open file for writing
$file = fopen('words.csv', 'w');

// Write remaining lines to file
foreach ($data as $fields) {
    fputcsv($file, $fields);
}
fclose($file);

Upvotes: 4

Serpes
Serpes

Reputation: 672

You have some errors in your code. The first one is that fgetcsv function only gets one line so if you want to extract all the lines you need a loop. The same happens with fputcsv function.

The other one is that array_shift function returns the shifted value so you are assigning to $data the string you don't need.

So, I think your code must be like:

$file = fopen('words.csv', 'r');
$data=array();
while (($data_tmp = fgetcsv($file, 1000, ",")) !== FALSE) {
       $data[] = $data_tmp;
}
fclose($file);
array_shift($data);
$file = fopen('words.csv', 'w');
foreach($data as $d){
    fputcsv($file,$d);
}
fclose($file);

Upvotes: 0

Related Questions