PHP – Writing to a file with php

 

Reading and writing always come together. Thus, after presenting the way to read from a file, now it is time to be able to write:

printing_to_file

 

Writing in PHP is not a challenge, the only tricky part is to know how to make a new line. 🙂

In my code, I am using the following –     $new_line = chr(13) . chr(10);

The rest is easy to understand and quite trivial:

fopen("readme.txt","w");
    if (!$fp)
    {
        echo "I cannot open the file!";
        exit;
    }
    
    $new_line = chr(13) . chr(10);
    fputs ($fp, "VitoshAcademy Proudly Printing:$new_line");
    
    for($i=10; $i<=500; $i+=10)
    {
        fputs($fp, "$i$new_line");
    }
    fputs ($fp, "End of the proud print!");
    echo "The request has been printed!";
    fclose($fp);
?>

Enjoy it!