in Software Development #PHP

How to write files to disk with PHP

Saving files to disk is a pretty simple task in PHP with file_put_contents(). Here's how to write a string to a file:

$string = 'I AM STRING!!';
file_put_contents('/path/to/destination', $string);

It is generally good practice to only do with when you are dealing with smaller strings as you can run into memory errors if you are trying to assemble a super large string. In situations where this may occur, you can rely on our trusty filesystem functions and write to the file line by line:

$file = fopen('/path/to/destination', 'w');

for ($i = 0; $i <= 1000000; $i++) { fwrite($file, $i . "\n"); }

fclose($file);

For the most part file_put_contents will get the job done, but if not, you can still get the job done!