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

来源:互联网 发布:pr淘宝视频 编辑:程序博客网 时间:2024/06/06 12:34

*************介绍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);
0 0
原创粉丝点击