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);
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);
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 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!