How to write into a file in PHP?


Question

I have this script on one free PHP-supporting server:

<html>
<body>

<?php
$file = fopen("lidn.txt","a");


fclose($file);
?>

</body>
</html>

It creates the file lidn.txt, but it's empty.

How can I create a file and write something into it, for example the line "Cats chase mice"?

1
79
4/30/2018 1:12:54 AM

Accepted Answer

You can use a higher-level function like file_put_contents($filename, $content) which is identical to calling fopen(), fwrite(), and fclose() successively to write data to a file.

Docs: file_put_contents

109
4/30/2018 1:07:54 AM

Consider fwrite():

<?php
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase mice');
fclose($fp);
?>

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon