zoukankan      html  css  js  c++  java
  • 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 ?>
  • 相关阅读:
    EasyUI 常用图标
    DataGridView滚动条联动
    FTP下载工具
    C# 解析带命名空间的xml
    1.基于3.x版本vue脚手架创建新项目
    js处理异步的几种方式
    JS字符串常用方法
    git(开源的分布式版本控制系统)
    js检查数据类型的方法
    数组的常用方法
  • 原文地址:https://www.cnblogs.com/hell0x/p/5135242.html
Copyright © 2011-2022 走看看