Save the contents of an array in a .txt using PHP foreach

2

I'm looking for how to save the contents of an array in .txt:

<?php
$resul = array('hermaniribeiro', 'Ebtsama', 'BrittoOFC', 'CheesterG', 'dsolutec', 'ExpoGanSon', 'dsolutec', 'ExpoGanSon', 'dsolutec', 'BelforFx', 'kunakrec', 'YouTube', 'Dasabuvir', 'greentechmedia', 'bardomsw', 'MdeMotion', 'iAnonymous', 'WilliamCorvera', 'MadridVen', 'Bertty17', 'SoyBobMarley', 'joseapontefelip', 'la_patilla', 'hootsuite', 'fawkestar70', 'starwars');

$file = fopen("user.txt", "a");
foreach($resul as $final){
fwrite($file, PHP_EOL ."$final");
}
 fclose($file);
?>

I try it that way but it only prints the result but it does not save it and what I'm looking for is to save it as it prints it with line break.

    
asked by BotXtrem Solutions 30.09.2017 в 04:20
source

2 answers

2

Good morning,

An array is a dynamic object class, so it would not serve to host static content (without server-side intervention). However, you can use a serialized language such as JSON.

Use json_encode() to carry out the saving, and to avoid confusion, I suggest that you modify the file name to extension .json

If this is not the case and you simply want to host a content to the fast you can use a loop like foreach

$nombres = [];
$contenido = "";
foreach($nombres as $nombre){
  $contenido .= $nombre."\n";
}
file_put_contents(__DIR__."/nombres.json", $contenido);

I hope I have helped you and have a nice night

    
answered by 30.09.2017 / 04:25
source
1

The write-only open option 'w' of fopen () fopen("user.txt", "w"); will truncate the previous content, so at the end of the iteration will only have the last value of the array in the file.

Two important things, for each iteration I would be opening the (fopen) file   and closing (fclose) user.txt , which is incorrect should be outside the bucle , in addition the end of line would go after the value (for more consistency if not your file will start with a line break) .

$resul = array('hermaniribeiro', 'Ebtsama', 'BrittoOFC', 'CheesterG', 'dsolutec', 'ExpoGanSon', 'dsolutec', 'ExpoGanSon', 'dsolutec', 'BelforFx', 'kunakrec', 'YouTube', 'Dasabuvir', 'greentechmedia', 'bardomsw', 'MdeMotion', 'iAnonymous', 'WilliamCorvera', 'MadridVen', 'Bertty17', 'SoyBobMarley', 'joseapontefelip', 'la_patilla', 'hootsuite', 'fawkestar70', 'starwars');

$file = fopen("user.txt", "w"); // Abrir
foreach($resul as $final) {
    fwrite($file, $final.PHP_EOL);
}
fclose($file); // Cerrar
    
answered by 30.09.2017 в 04:29