2010-03-15 5 views
13

Come si fa ad aprire un file di testo e scrivere con php appendstyleCome aprire file di testo e scrivere in append-style con php?

textFile.txt 

     //caught these variables 
     $var1 = $_POST['string1']; 
     $var2 = $_POST['string2']; 
     $var3 = $_POST['string3']; 

    $handle = fopen("textFile.txt", "w"); 
    fwrite = ("%s %s %s\n", $var1, $var2, $var3, handle);//not the way to append to textfile 
fclose($handle); 

risposta

25

per aggiungere dati in un file si avrebbe bisogno di aprire il file in modalità append (vedi fopen):

  • 'a'
    Aperto solo per scrittura; posiziona il puntatore del file alla fine del file. Se il file non esiste, provare a crearlo.
  • 'a +'
    Aperto per lettura e scrittura; posiziona il puntatore del file alla fine del file. Se il file non esiste, provare a crearlo.

Quindi, per aprire il textfile.txt in scrittura accodare solo modalità:

fopen("textFile.txt", "a") 

ma si può anche usare la funzione più semplice file_put_contents che combina fopen, fwrite e fclose in uno Funzione:

$data = sprintf("%s %s %s\n", $var1, $var2, $var3); 
file_put_contents('textFile.txt', $data, FILE_APPEND); 
+2

+ 1 per entrare nei dettagli. 'fprintf()' sarebbe anche una buona scelta. –