write to a file in php

There are several ways to write to a file in PHP, but two common methods are fwrite and file_put_contents.

Using fwrite

This method requires opening the file in "write" mode using the fopen function, and then using the fwrite function to write the data to the file.

Here is an example:

main.php
$file = fopen("example.txt","w");
fwrite($file,"Hello World. Testing!");
fclose($file);
88 chars
4 lines

This code will create a new file called example.txt (if it doesn't exist) and write the string "Hello World. Testing!" to it.

Using file_put_contents

This method is simpler and more concise. It allows you to write data to a file with just one line of code:

main.php
file_put_contents("example.txt", "Hello World. Testing!");
59 chars
2 lines

This code will create a new file called example.txt (if it doesn't exist) and write the string "Hello World. Testing!" to it. Unlike fwrite, this method automatically closes the file when done.

gistlibby LogSnag