Current Location: Home> Latest Articles> PHP File Reading and Writing Practical Tutorial: Master Basic File Operations and Techniques

PHP File Reading and Writing Practical Tutorial: Master Basic File Operations and Techniques

M66 2025-06-25

PHP File Reading and Writing Practical Tutorial: Master Basic File Operations and Techniques

PHP is a widely used scripting language in web development, known for its flexible and powerful file handling capabilities. This tutorial will introduce the most commonly used methods for reading and writing files in PHP, along with practical code examples to help developers quickly master these techniques.

1. File Reading

1. Using the file_get_contents() function to read the entire file content

$file_path = "example.txt";
$file_content = file_get_contents($file_path);
echo $file_content;

2. Reading file content line by line

$file_path = "example.txt";
$file_handle = fopen($file_path, "r");
<p>while (!feof($file_handle)) {<br>
$line = fgets($file_handle);<br>
echo $line;<br>
}</p>
<p>fclose($file_handle);<br>

3. Reading a CSV file and processing data

$file_path = "example.csv";
$file_handle = fopen($file_path, "r");
<p>$data = array();<br>
while (($line = fgetcsv($file_handle)) !== false) {<br>
$data[] = $line;<br>
}</p>
<p>fclose($file_handle);<br>
print_r($data);<br>

2. File Writing

1. Using the file_put_contents() function to overwrite content

$file_path = "example.txt";
$file_content = "Hello, world!";
file_put_contents($file_path, $file_content);

2. Using fwrite() to append content to a file

$file_path = "example.txt";
$file_handle = fopen($file_path, "a");
$file_content = "This is a new line.";
fwrite($file_handle, $file_content);
fclose($file_handle);

3. Writing an array to a CSV file

$file_path = "example.csv";
$file_handle = fopen($file_path, "w");
<p>$data = array(<br>
array("Name", "Age", "Email"),<br>
array("John Doe", "30", "<a class="cursor-pointer" rel="noopener">johndoe@example.com</a>"),<br>
array("Jane Smith", "25", "<a class="cursor-pointer" rel="noopener">janesmith@example.com</a>")<br>
);</p>
<p>foreach ($data as $line) {<br>
fputcsv($file_handle, $line);<br>
}</p>
<p>fclose($file_handle);<br>

Summary

Through this tutorial, we have explored the most common PHP file reading and writing methods, explained in detail with code examples. Mastering these basic reading and writing techniques is invaluable for web development and data processing. We hope that readers can deepen their understanding of PHP file operations through learning and practice, and apply them flexibly in real-world projects.