您的当前位置:首页>全部文章>文章详情

PHP写入文件的方法,读取文件内容的五种方式

发表于:2022-05-05 15:20:54浏览:906次TAG: #PHP #写入文件 #读取文件

首先是写入把一个字符串写入文件中
使用的是file_put_contents()函数。该函数访问文件时,遵循以下规则:

  • 如果设置了 FILE_USE_INCLUDE_PATH,那么将检查 filename 副本的内置路径
  • 如果文件不存在,将创建一个文件
  • 打开文件
  • 如果设置了 LOCK_EX,那么将锁定文件
  • 如果设置了 FILE_APPEND,那么将移至文件末尾。否则,将会清除文件的内容
  • 向文件中写入数据
  • 关闭文件并对所有文件解锁
  • 如果成功,该函数将返回写入文件中的字符数。如果失败,则返回 False。
    示例:
    <?php
    file_put_contents("sites.txt","Runoob");
    ?>
    
    接下来我们向文件 sites.txt 追加内容:
    <?php
    $file = 'sites.txt';
    $site = "\nGoogle";
    // 向文件追加写入内容
    // 使用 FILE_APPEND 标记,可以在文件末尾追加内容
    //  LOCK_EX 标记可以防止多人同时写入
    file_put_contents($file, $site, FILE_APPEND | LOCK_EX);
    ?>
    

其次是读取文件内容的五种方式:
1、指定读取大小,这里把整个文件内容读取出来

<?php
$file_path = "test.txt";
if (file_exists($file_path)) {
    $fp = fopen($file_path, "r");
    $str = fread($fp, filesize($file_path));//指定读取大小,这里把整个文件内容读取出来
    echo $str = str_replace("\r\n", "<br />", $str);
}
?>

2、将整个文件内容读入到一个字符串中

<?php
$file_path = "test.txt";
if (file_exists($file_path)) {
    $str = file_get_contents($file_path);//将整个文件内容读入到一个字符串中
    $str = str_replace("\r\n", "<br />", $str);
    echo $str;
}
?>

3、循环读取,直至读取完整个文件

<?php
$file_path = "test.txt";
if (file_exists($file_path)) {
    $fp = fopen($file_path, "r");
    $str = "";
    $buffer = 1024;//每次读取 1024 字节
    while (!feof($fp)) {//循环读取,直至读取完整个文件
        $str .= fread($fp, $buffer);
    }
    $str = str_replace("\r\n", "<br />", $str);
    echo $str;
}
?>

4、逐行读取文件内容

<?php
$file_path = "test.txt";
if (file_exists($file_path)) {
    $file_arr = file($file_path);
    for ($i = 0; $i < count($file_arr); $i++) {//逐行读取文件内容
        echo $file_arr[$i] . "<br />";
    }
    /*
    foreach($file_arr as $value){
    echo $value."<br />";
    }*/
}
?>

5、逐行读取。如果fgets不写length参数,默认是读取1k

<?php
$file_path = "test.txt";
if (file_exists($file_path)) {
    $fp = fopen($file_path, "r");
    $str = "";
    while (!feof($fp)) {
        $str .= fgets($fp);//逐行读取。如果fgets不写length参数,默认是读取1k。
    }
    $str = str_replace("\r\n", "<br />", $str);
    echo $str;
}
?>