Current Location: Home> Latest Articles> PHP File Handling Tutorial: Detailed File Read and Write Techniques

PHP File Handling Tutorial: Detailed File Read and Write Techniques

M66 2025-06-25

PHP File Handling Tutorial: Detailed File Read and Write Techniques

Introduction

PHP is a widely used scripting language for web development, and it offers powerful and flexible file handling capabilities. This tutorial introduces commonly used file reading and writing methods in PHP, providing practical code examples to help readers quickly master these techniques.

1. File Reading

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

  <?php
  $file_path = "example.txt";
  $file_content = file_get_contents($file_path);
  echo $file_content;
  ?>
  

2. Reading file content line by line

  <?php
  $file_path = "example.txt";
  $file_handle = fopen($file_path, "r");

  while (!feof($file_handle)) {
      $line = fgets($file_handle);
      echo $line;
  }

  fclose($file_handle);
  ?>
  

3. Reading CSV files and processing data

  <?php
  $file_path = "example.csv";
  $file_handle = fopen($file_path, "r");

  $data = array();
  while (($line = fgetcsv($file_handle)) !== false) {
      $data[] = $line;
  }

  fclose($file_handle);
  print_r($data);
  ?>
  

2. File Writing

1. Using the file_put_contents() function to overwrite content

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

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

  <?php
  $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

  <?php
  $file_path = "example.csv";
  $file_handle = fopen($file_path, "w");

  $data = array(
      array("Name", "Age", "Email"),
      array("John Doe", "30", "johndoe@example.com"),
      array("Jane Smith", "25", "janesmith@example.com")
  );

  foreach ($data as $line) {
      fputcsv($file_handle, $line);
  }

  fclose($file_handle);
  ?>
  

Conclusion

Through this tutorial, we have learned about commonly used file reading and writing methods in PHP, with detailed code examples explaining each. Mastering these basic file operations is very useful for web development and data processing. We hope readers will gain a deeper understanding of PHP file operations and apply these skills flexibly in their real-world projects.