php 文件读取和写入详细介绍例子

本文介绍了如何使用PHP进行文件的读取和写入操作。详细解释了覆盖写入、追加写入及换行写入的方法,并展示了如何通过fgets和fread等函数来读取文件内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

*************介绍PHP文件的写入 和 读取**************

/**

*文件写入

*/

//覆盖写入

$filename = 'leyangjun.txt';
$word = "北京欢迎你!";
$fh = fopen($filename, "w");
echo fwrite($fh, $word);
fclose($fh);

//追加写入
$filename = 'leyangjun.txt';
$word = "你好!";
$fh = fopen($filename, "a"); //参数选择 a ,则表示在文件后面追加写入:
echo fwrite($fh, $word);
fclose($fh);

//换行写入
$filename = 'leyangjun.txt';
$word = "北京欢迎你!\r\n"; // \r\n换行
$fh = fopen($filename, "a");
echo fwrite($fh, $word);
fclose($fh);

//写封装
$filename = 'leyangjun.txt';
$word = "北京欢迎你!\r\n";
// 确定文件存在并且可写
if (is_writable($filename)) {
    //打开文件
    if (!$fh = fopen($filename, 'a')) {
         echo "不能打开文件 $filename";
         exit;
    }
    // 写入内容
    if (fwrite($fh, $word) === FALSE) {
        echo "不能写入到文件 $filename";
        exit;

    }

    $fh = fopen($filename, "a"); //参数选择 a ,则表示在文件后面追加写入:
    fwrite($fh, $word);

    echo "成功地将 $word 写入到文件 $filename";
    fclose($fh);
} else {
    echo "文件 $filename 不可写";
}


/**

 *文件读取

 */
//读取文件内容,字符串输出
$myfile = fopen("leyangjun.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("leyangjun.txt"));
fclose($myfile);

//fgets()函数用于从文件读取单行。
$myfile = fopen("leyangjun.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);

//推荐--->逐行读取(feof()函数检查是否已到达 "end-of-file",对于遍历未知长度的数据很有用)
$myfile = fopen("leyangjun.txt", "r") or die("Unable to open file!");
// 输出单行直到 end-of-file
while(!feof($myfile)) {
  echo fgets($myfile) . "<br>";
}
fclose($myfile);

//fgetc()函数用于从文件中读取单个字符。
$myfile = fopen("leyangjun.txt", "r") or die("Unable to open file!");
// 输出单字符直到 end-of-file
while(!feof($myfile)) {
  echo fgetc($myfile);
}
fclose($myfile);

//你可以把你拿到的字符存储到你的逻辑中处理
$fp = fopen("leyangjun.txt", "r");
$arrData = array();
while(! feof($fp)){   
    $arrData[] = fgets($fp);
}
echo '<pre>';print_r($arrData);exit;
fclose($fp);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值