• PHP获取文件内容的几种方法


    1.file_get_contents得到文件的内容

     1 <?php
     2     header("content-type:text/html;charset=utf-8");
     3 
     4     $file_path = 'lock.txt';
     5 
     6     $conn = file_get_contents($file_path);
     7     $conn = str_replace("
    ", "<br/>", $conn);
     8     echo $conn;
     9     fclose($conn);
    10 ?>

    2.用fopen+fgets得到文件内容

     1 <?php
     2     header("content-type:text/html;charset=utf-8");
     3 
     4     $file_path = 'lock.txt';
     5 
     6     if(file_exists($file_path)){
     7         if($fp = fopen($file_path,'a+')){
     8             while(!feof($fp)){
     9                 $conn = fgets($fp);
    10                 $conn = str_replace("
    ", "<br/>", $conn);
    11                 echo $conn;
    12             }
    13         }else{
    14             echo "文件打不开";
    15         }
    16     }else{
    17         echo "没有这个文件";
    18     }
    19     fclose($fp);
    20 ?>

    3.用fopen+fread获得文件内容

     1 <?php
     2     header("content-type:text/html;charset=utf-8");
     3 
     4     $file_path = 'lock.txt';
     5 
     6     if(file_exists($file_path)){
     7         if($fp = fopen($file_path,'a+')){
     8             $conn = fread($fp, filesize($file_path));
     9             $conn = str_replace("
    ", "<br/>", $conn);
    10             echo $conn;
    11             }
    12         }else{
    13             echo "文件打不开";
    14         }
    15     }else{
    16         echo "没有这个文件";
    17     }
    18     fclose($fp);
    19 ?>

    4.循环读取获得文件内容

     1 <?php
     2     header("content-type:text/html;charset=utf-8");
     3 
     4     $file_path = 'lock.txt';
     5 
     6     if(file_exists($file_path)){
     7         if($fp = fopen($file_path,'a+')){
     8             $buffer=1024; 
     9             $str=""; 
    10             while(!feof($fp)){ 
    11             $str.=fread($fp,$buffer); 
    12             }
    13             $str=str_replace("
    ","<br>",$str); 
    14             echo $str; 
    15         }else{
    16             echo "文件打不开";
    17         }
    18     }else{
    19         echo "没有这个文件";
    20     }
    21     fclose($fp);
    22 ?>
  • 相关阅读:
    RichEdit
    用 RAD Studio 柏林版创建 IoT 应用程序
    延时程序
    SQL if exists用法
    Firemonkey限制TEdit只能输入数字的完美方法
    leetcode 树
    leetcode string
    clone-graph
    surrounded-regions merge-intervals
    leetcode链表题
  • 原文地址:https://www.cnblogs.com/hell0x/p/5135242.html
Copyright © 2020-2023  润新知