Home > Backend Development > PHP Tutorial > PHP file programming (2) - four ways to read files

PHP file programming (2) - four ways to read files

WBOY
Release: 2016-07-25 08:59:26
Original
1076 people have browsed it
  1. //Read file

  2. $file_path="text.txt";

  3. if(!file_exists($file_path)){

  4. echo "File does not exist";
  5. exit();
  6. }
  7. //Open the file
  8. $fp=fopen($file_path,"a+");
  9. //Read the file
  10. $content=fread($fp, filesize($file_path));
  11. echo "The content of the file is:
    ";
  12. //By default, after the content is output to the web page, it will not be displayed in a new line because the web page does not recognize rn
  13. //All required Put rn =>
  14. $content=str_replace("rn","
    ",$content);
  15. echo $content;

  16. fclose($fp);

  17. ?>

Copy code

2. The second way to read files

  1. //The second way to read files

  2. $file_path="text.txt";

  3. if(!file_exists ($file_path)){
  4. echo "File does not exist";
  5. exit();
  6. }
  7. $content=file_get_contents($file_path);

  8. $content=str_replace("rn", "
    ",$content);

  9. echo $content;
  10. ?>

Copy code

3. How to read in a loop (to deal with large files)

  1. //The third reading method, loop reading (for large files)

  2. $file_path="text.txt ";

  3. if(!file_exists($file_path)){
  4. echo "The file does not exist";
  5. exit();
  6. }

  7. //Open the file

  8. $fp=fopen($file_path ,"a+");
  9. //Define how many bytes to read each time
  10. $buffer=1024;
  11. //Read simultaneously. Determine whether the end of the file is reached while(!feof($fp)){
  12. //Read data in 1024 bytes
  13. $content=fread($fp,$buffer);
  14. echo $content;
  15. }< /p>
  16. fclose($fp);

  17. ?>

Copy the code
4. Read the ini configuration file 1), db.ini file

  1. $arr=parse_ini_file("db.ini");

  2. echo "
    ";
  3. print_r($arr);
  4. echo "";
  5. echo $arr['host'];

  6. //Connect to the database

  7. $conn = mysql_connect($arr['host'], $arr['user'] , $arr['pwd']);

  8. if(!$conn){

  9. echo "error";
  10. }

  11. echo "OK";

  12. ?>

Copy code

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template