Save to output file .txt

1

I have a code that reads a file and does a series of functions to it. I do not know very well how I could save the file once its modifications were made in a file.txt. Can you guide me? Here I leave my code

<?php
$fp = fopen("archivo.txt", "r");

$linea = fgets($fp);
echo $linea;


echo '<br>';
echo '<br>';

$texto = " <b><font size=\"4\"> <span style='color:black;font-weight:bold;'>PALABRAS</span><font size=\"6\"></b> ";
echo $texto;
echo  '<br>';
echo '<br>';
echo str_word_count(file_get_contents("archivo.txt"));

echo '<br>';
echo '<br>';


$texto = " <b></b> <font size=\"4\"> <span style='color:black;font-weight:bold;'>NUEVO TEXTO</span>";

echo $texto;

echo '<br>';

echo '<br>';

echo eliminarVocales($linea);

function eliminarVocales($frase) {
  $vocales = array("a", "e", "i", "o", "u", "A", "I", "O", "U");
  return str_replace($vocales, "", $frase);

}
fclose($fp);

?>
    
asked by Juan 11.10.2018 в 17:37
source

1 answer

1

To start I recommend that you read the permits that you can pass to fopen link

As you can see, you are only passing reading permissions, so you can not modify the file, to pass write permissions you have to use rw or w+

Then you would have to store the text in a variable that would be the new text, so instead of doing the echos you would have to store them in a variable

to finish you should only use fwrite (Documentation of fwrite: link )

Your code would be like this

 <?php
    $fp = fopen("archivo.txt", "rw");

    $linea = fgets($fp);
    echo $linea;


    echo '<br>';
    echo '<br>';

    $texto = " <b><font size=\"4\"> <span style='color:black;font-weight:bold;'>PALABRAS</span><font size=\"6\"></b> ";
    echo $texto;
    echo  '<br>';
    echo '<br>';
    echo str_word_count(file_get_contents("archivo.txt"));

    echo '<br>';
    echo '<br>';


    $texto = " <b></b> <font size=\"4\"> <span style='color:black;font-weight:bold;'>NUEVO TEXTO</span>";

    echo $texto;

    echo '<br>';

    echo '<br>';

    $fileText =  eliminarVocales($linea);
    echo $fileText;

    fwrite($fp, $fileText);
    fclose($fp);

     function eliminarVocales($frase) {
      $vocales = array("a", "e", "i", "o", "u", "A", "I", "O", "U");
      return str_replace($vocales, "", $frase);

    }

    ?>
    
answered by 11.10.2018 / 18:33
source