How to remove rows from CSV file using PHP?

-3

I need to remove the first two rows from a CSV file, does it have any function for this in PHP?

    
asked by anonymous 04.07.2018 / 16:08

2 answers

0

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

Example relatorio.csv :

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

The code looks 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"
}

Note: fseek places the file reading from the line that is entered. PHP counts the lines of the file from 0 .

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

See:

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

Note : Only use the second example if the size of the CSV is small, because depending on the line quantity, you may overload memory, because file reads each line to array .

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

    
05.07.2018 / 19:36
-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 do not want to overwrite the file, just ignore the last 7 lines of code and use the $dados array.

    
04.07.2018 / 16:28