Home >Backend Development >PHP Tutorial >Why is My PHP File Empty After Using `fopen()` and `fclose()`?
Writing Into a File in PHP
This question arose when a user attempted to create and write to a text file using fopen() and fclose() functions, but the file remained empty after execution.
The solution lies in employing higher-level functions such as file_put_contents(). This function seamlessly performs the tasks of opening, writing, and closing a file, similar to using fopen(), fwrite(), and fclose() independently.
The syntax for file_put_contents() is:
file_put_contents($filename, $content);
where $filename specifies the path to the file to be created or modified, and $content represents the data to be written.
For example, to create a file named "lidn.txt" and write the line "Cats chase mice" into it, you can use the following code:
file_put_contents("lidn.txt", "Cats chase mice");
This code will create the file "lidn.txt" if it doesn't exist and write the specified line into it.
The above is the detailed content of Why is My PHP File Empty After Using `fopen()` and `fclose()`?. For more information, please follow other related articles on the PHP Chinese website!