Home > Backend Development > PHP Tutorial > Why is My PHP File Empty After Using `fopen()` and `fclose()`?

Why is My PHP File Empty After Using `fopen()` and `fclose()`?

Mary-Kate Olsen
Release: 2024-11-23 05:51:15
Original
279 people have browsed it

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);
Copy after login

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");
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template