Usando php, cómo insertar texto sin sobrescribir al principio de un archivo de texto

StackOverflow https://stackoverflow.com/questions/103593

  •  01-07-2019
  •  | 
  •  

Pregunta

Tengo:

<?php

$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");

if ($_POST["lastname"] <> "")
{
   fwrite($file,$_POST["lastname"]."\n");
}

fclose($file);

?>

pero sobrescribe el comienzo del archivo.¿Cómo hago para que se inserte?

¿Fue útil?

Solución

No estoy completamente seguro de su pregunta: ¿desea escribir datos y no sobrescribir el comienzo de un archivo existente, o escribir datos nuevos al comienzo de un archivo existente, manteniendo el contenido existente después?

Para insertar texto sin sobrescribir el comienzo del archivo, tendrás que abrirlo para agregar (a+ en vez de r+)

$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");

if ($_POST["lastname"] <> "")
{
   fwrite($file,$_POST["lastname"]."\n");
}

fclose($file);

Si estás intentando escribir al inicio del archivo, tendrás que leer el contenido del archivo (ver file_get_contents) primero, luego escriba su nueva cadena seguida del contenido del archivo en el archivo de salida.

$old_content = file_get_contents($file);
fwrite($file, $new_content."\n".$old_content);

El enfoque anterior funcionará con archivos pequeños, pero es posible que se encuentre con límites de memoria al intentar leer un archivo grande al usar file_get_conents.En este caso, considere usar rewind($file), que establece el indicador de posición del archivo para el identificador al comienzo de la secuencia del archivo.Nota al usar rewind(), para no abrir el archivo con el a (o a+) opciones, como:

Si ha abierto el archivo en modo agregar ("a" o "a+"), cualquier dato que escriba en el archivo siempre se agregará, independientemente de la posición del archivo.

Otros consejos

Un ejemplo práctico para insertar en medio de una secuencia de archivos sin sobrescribir y sin tener que cargar todo en una variable/memoria:

function finsert($handle, $string, $bufferSize = 16384) {
    $insertionPoint = ftell($handle);

    // Create a temp file to stream into
    $tempPath = tempnam(sys_get_temp_dir(), "file-chainer");
    $lastPartHandle = fopen($tempPath, "w+");

    // Read in everything from the insertion point and forward
    while (!feof($handle)) {
        fwrite($lastPartHandle, fread($handle, $bufferSize), $bufferSize);
    }

    // Rewind to the insertion point
    fseek($handle, $insertionPoint);

    // Rewind the temporary stream
    rewind($lastPartHandle);

    // Write back everything starting with the string to insert
    fwrite($handle, $string);
    while (!feof($lastPartHandle)) {
        fwrite($handle, fread($lastPartHandle, $bufferSize), $bufferSize);
    }

    // Close the last part handle and delete it
    fclose($lastPartHandle);
    unlink($tempPath);

    // Re-set pointer
    fseek($handle, $insertionPoint + strlen($string));
}

$handle = fopen("file.txt", "w+");
fwrite($handle, "foobar");
rewind($handle);
finsert($handle, "baz");

// File stream is now: bazfoobar

La biblioteca del compositor se puede encontrar aquí

Obtienes lo mismo al abrir el archivo para agregarlo.

<?php
$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
   fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
?>

Si desea colocar su texto al principio del archivo, primero deberá leer el contenido del archivo, como:

<?php

$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");

if ($_POST["lastname"] <> "")
{    
    $existingText = file_get_contents($file);
    fwrite($file, $existingText . $_POST["lastname"]."\n");
}

fclose($file);

?>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top