Current Location: Home> Latest Articles> PHP File Operations: How to Write and Read English Content in PHP

PHP File Operations: How to Write and Read English Content in PHP

M66 2025-07-03

PHP File Operations: How to Write English Content

Performing English content writing operations in PHP is a common file handling task. This article will demonstrate how to use PHP to write English text to a file with detailed code examples.

Open File and Write English Content

We first need to use PHP's fopen() function to open a file and use fwrite() to write English content to it. Below is the code example:

<?php
$file = fopen("english.txt", "w") or die("Unable to open file!");
$text = "Hello, this is a sample text written in English.";
fwrite($file, $text);
fclose($file);
echo "Successfully wrote English content to the file!";
?>

In this code, we use fopen() to open the file named english.txt with write mode ("w"). Then, we assign the English text to the $text variable and write it to the file using fwrite(). Finally, we close the file with fclose() and output a success message.

Verify the Written English Content

To ensure the English content has been written to the file successfully, we can read the file back and display its contents. Here's the code to read and display the content:

<?php
$file = fopen("english.txt", "r") or die("Unable to open file!");
$text = fread($file, filesize("english.txt"));
fclose($file);
echo "The English content read is: " . $text;
?>

In this code, we use fopen() with read mode ("r") to open the file, then fread() is used to read the content. The content is assigned to the $text variable and displayed using echo.

Conclusion

Through these operations, we have demonstrated how to write English content to a file using PHP and how to read and display that content. These operations are crucial for website development, logging, and data storage scenarios.