Delete the first line of an array and store result (php)

2

I am looking for the correct way to open a text file to upload the content to a

  

array

Delete the first line and save the content in the same text file again.

without the deleted line I use this example:

<?php
$ra= file("datos.txt");
$s = unset($ra[0]);

$file = fopen("datos.txt", "w");
fwrite($file,$s);
fclose($file);
?>

The problem is that the result is a text file without content.

I hope some idea.

    
asked by BotXtrem Solutions 29.09.2017 в 21:29
source

1 answer

1

Here is an example: I hope it serves you. Greetings

<?php

// Inicializamos nuestras variables
$i=0; //contador de línea que se está leyendo
$numlinea = 0; //línea que se desea borrar a esa se le asigna el indice, iniciando en 0 como primera 
$aux = array();

// Abrimos el archivo
$archivo = fopen('datos.txt','r');
if($archivo){
// Hacemos un ciclo y vamos recogiendo linea por linea del archivo.
    while ($linea = fgets($archivo))
    {

  if ($i != $numlinea)  // Si la linea que deseamos eliminar no es esta 
  {
    $aux[] = $linea; // La agregamos a nuestra variable auxiliar
}

  // Incrementamos nuestro contador de lineas
$i++;
}

// Cerramos el archivo.
fclose($archivo);

// Convertimos el arreglo(array) en una cadena de texto (string) para guardarlo.
$aux = implode($aux, '');

// Reemplazamos el contenido del archivo con la cadena de texto (sin la linea eliminada)
file_put_contents('datos.txt', $aux);
echo "Se elimino la linea '$numlinea'";
}else{
    echo "Ocurrio un error al abrir el archivo";
}
?>;
    
answered by 29.09.2017 / 22:42
source