博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

PHP 文件编程(二)

Posted on 2013-05-12 01:30  Step at a time  阅读(287)  评论(0编辑  收藏  举报

1、读取文件操作

<?php

    //读取文件
    $file_path="text.txt";

    if(!file_exists($file_path)){
        echo "文件不存在";
        exit();
    }
    
    //打开文件
    $fp=fopen($file_path,"a+");
    //读取文件
    $content=fread($fp,filesize($file_path));
    echo "文件内容是:<br/>";
    //默认情况下把内容输出到网页后,不会换行显示,因为网页不识别\r\n
    //所有要把\r\n =><br/>
    
    $content=str_replace("\r\n","<br/>",$content);
    echo  $content;

    fclose($fp);
?>

2、第二种读取文件的方式

<?php


    //第二种读取文件的方式

    $file_path="text.txt";
    if(!file_exists($file_path)){
        echo "文件不存在";
        exit();
    }
    $content=file_get_contents($file_path);

    $content=str_replace("\r\n","<br/>",$content);
    echo  $content;
?>

3、第三种读取方法,循环读取(对付大文件)

<?php


    //第三种读取方法,循环读取(对付大文件)

    $file_path="text.txt";
    if(!file_exists($file_path)){
        echo "文件不存在";
        exit();
    }

    //打开文件
    $fp=fopen($file_path,"a+");
    //定义每次读取的多少字节
    $buffer=1024;
    //一边读取。一边判断是否达到文件末尾
    while(!feof($fp)){
        //按1024个字节读取数据
        $content=fread($fp,$buffer);
        echo $content;
    }

    fclose($fp);
?>

 4、文件读取实际应用:当我们连接数据库的时候,可以把指定的数据配置到一个文件中,然后再PHP运行时,实时获取信息

db.ini 文件

host=127.0.0.1
user=root
pwd=root
db=test

获取文件

<?php

    $arr=parse_ini_file("db.ini");
    echo "<pre>";
    print_r($arr);
    echo "</pre>";
    
    echo $arr['host'];

    //连接数据库
    $conn = mysql_connect($arr['host'], $arr['user'], $arr['pwd']);

    if(!$conn){
        echo "error";
    }

    echo "OK";
?>