三,读取文件

1,读取文件函数有

(1) fread(文件名称,读取大小),比如fread($file_path,filesize($file_path));

(2) file_get_contents(文件名称,此函数实际包含fopen(文件)+fread(文件)+fclose(文件));

,2,读取文件方式有三种 

第一种读取文件方式:

/*第一种读取文件方式*/
$file_path = "test.txt";
if(file_exists($file_path)){
    //打开文件
    $fp = fopen($file_path,"a+");
    //读内容,并输入
    $conn = fread($fp,filesize($file_path));
    echo "文件的内容是:<br/>";
    //网页中换行符是<br/>,文本中换行符是\r\n,需要替换换行符
    $conn = str_replace("\r\n","<br/>",$conn);
    echo $conn;
    fclose($file_path);
}else{
    echo '文件不存在!';
}

  第二种读取文件方式:

/*第二种读取文件方式*/
$file_path = "test.txt";
$conn = file_get_contents($file_path);
$conn = str_replace("\r\n","<br/>",$conn);
echo $conn;

  第三种读取文件方式:

/*前两种方式存在缺陷,如果读取文件过大,则容易出错,因此推荐第三种方式*/
/*第三种读取文件方式*/
$file_path = "test.txt";
if(file_exists($file_path)){
    $fp = fopen($file_path,"a+");
    $buffer = 1024;
    $str = "";
    while(!feof($fb)){
        $str .= fread($fp,$buffer);
    }
 
    $str = str_replace("\r\n","<br/>",$str);
    echo $str;
    fclose($file_path);
}else{
    echo "文件不存在!";
}

  

posted on 2016-08-02 18:27  张三的哥哥  阅读(380)  评论(0编辑  收藏  举报