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. Do you know any way?
<?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);
?>
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 that you can not modify the file, to pass write permission 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 (fwrite documentation: link )
Your code would be like this
$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);
}
?