How to remove CSV file lines using PHP?

Asked

Viewed 904 times

-1

I need to remove the first two lines of a CSV file, it has some function for this in PHP?

  • tried to use the Trim?

  • 1

    Your question is, whether there is a native function!?

  • fputcsv and fgetcsv (functions and methods of SplFileObject ) are good ways to work with CSV in PHP.

2 answers

1


I like to use the function SplFileObjectPHP. You can open the file and point to the line from which you want to read the file through the function seek.

Example relatorio.csv:

a1,b1,c1
a2,b2,c2
a3,b3,c3
a4,b4,c4
a5,b5,c5

The code would look like this:

$file = new \SplFileObject('relatorio.csv', 'r');

// Coloca o ponteiro na segunda linha do arquivo
$file->seek(1);

// continue o laço até que seja o fim da linha
while ($file->eof() === false) {
    // obtém o dado de uma linha do CSV
    var_dump($file->fgetcsv());
}

The result would be this:

array(3) {
  [0]=>
  string(2) "a3"
  [1]=>
  string(2) "b3"
  [2]=>
  string(2) "c3"
}
array(3) {
  [0]=>
  string(2) "a4"
  [1]=>
  string(2) "b4"
  [2]=>
  string(2) "c4"
}
array(3) {
  [0]=>
  string(2) "a5"
  [1]=>
  string(2) "b5"
  [2]=>
  string(2) "c5"
}

Remark: THE fseek puts the reading of the file from the informed line. PHP counts the file lines from the 0.

You can also use the function array_slice combined with file to get all lines from the file in the array. The file opens each line in a array, and the array_slice "cuts" the array at the indicated value.

Behold:

 var_dump(array_slice(file('relatorio.csv'), 2));

Observing: Only use the second example if the size of the CSV is small, because depending on the amount of line, it may overload the memory, because file reads each line for one array.

The first solution reads line by line, saving processing/memory.

  • 3

    Sensational, one-line solution for those who truly understand language. PS: if you can add a brief explanation about array_slice. The +1 is already guaranteed

  • Thank you so much for your help!

  • It’s the second unaccounted-for downvote that I get [and I don’t usually do that, I always comment on my negative votes]. Who did this could at least leave a comment to help people, who want to help the community grow, understand the reason for the negatives, to know what can be improved.

-2

It is possible to do this in PHP although it is not a single function as you asked:

// Leia o arquivo
$arquivo = fopen('seu_arquivo.csv', 'r');

// Pega todas as linhas do arquivo
while (($linha = fgetcsv($arquivo)) !== FALSE) {
  // Armazena as linhas em um array de dados
  $dados[] = $linha;
}
fclose($arquivo);

// Remove o primeiro elemento do array (ou seja, a primeira linha do arquivo que foi salva)
array_shift($dados);

// Faz novamente para removera segunda
array_shift($dados);

// Abre arquivo para escrita
$arquivo = fopen('seu_arquivo.csv', 'w');

// Escreve no arquivo as linhas salvas no array
foreach ($dados as $dado) {
    fputcsv($arquivo, $dado);
}
fclose($arquivo);

If you just want the data and don’t want to over-write the file, just ignore the last 7 lines of code and use the array $dados.

  • Young man, personally, I thought your code goes a long way towards making something simple and wasting more memory than it should.

  • @Wallacemaxters understood your opinion. The real difference between my code and yours is that by not using the seek() use 2 commands of array_shift() the more you and use foreach instead of while. Now if this is too much back for you. All right :) Thanks for the feedback.

  • 3

    In fact, you save all the lines of the CSV to another array. If the guy’s CSV had 30,000 lines, you’d have a lot of memory, which could cause a fatal error. I’m serious. The way I did, you read one file line at a time without "abusing" memory.

  • 3

    I could do it very quickly (similar to your solution) using just one line... var_dump(array_slice(file('arquivo.csv'), 1));, but I didn’t do it thinking about the memory

  • Hmm, now I get your point @Wallacemaxters thanks, I’ll check out a way to improve and modify the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.