Home > Backend Development > PHP Tutorial > How Do I Write Text to a File in PHP?

How Do I Write Text to a File in PHP?

Barbara Streisand
Release: 2024-11-28 20:12:12
Original
706 people have browsed it

How Do I Write Text to a File in PHP?

Writing into a File in PHP

You want to create a file and write some text into it, such as the line "Cats chase mice." Here's how you can accomplish this task in PHP:

Creating and Writing to a File

To write data into a file, you can use high-level functions like file_put_contents(). This function is equivalent to using fopen(), fwrite(), and fclose() successively.

$filename = 'lidn.txt';
$content = 'Cats chase mice';
file_put_contents($filename, $content);
Copy after login

This code opens the file specified by $filename, writes the content stored in $content to the file, and then closes the file. The file will be created if it doesn't exist, and its contents will be replaced with the new content.

Alternative Approach

If you prefer to use the lower-level functions fopen(), fwrite(), and fclose(), you can follow these steps:

$filename = 'lidn.txt';
$file = fopen($filename, 'w');
fwrite($file, 'Cats chase mice');
fclose($file);
Copy after login

In this approach, you open the file in write mode ('w'), write the desired content to the file, and close the file handle.

Additional Notes

  • The file_put_contents() function is preferred for its simplicity and compatibility across different PHP versions.
  • Make sure the file you're trying to write to has the appropriate file permissions to allow write access.
  • You can append content to an existing file by using the 'a' mode in fopen() or file_put_contents(). For example: file_put_contents('lidn.txt', 'Another line', FILE_APPEND)

The above is the detailed content of How Do I Write Text to a File in PHP?. 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