Home  >  Article  >  php教程  >  php读取文件与写入文件方法实例

php读取文件与写入文件方法实例

WBOY
WBOYOriginal
2016-06-08 17:23:35917browse

在php中读取文件我们需要使用file_get_contents或fopen来打开文件然后再读取了,file_get_contents函数读文件比fopen要方便,写文件需要fopen函数与file_put_contents或fwrite合作才可以实例下面我来介绍下。

<script>ec(2);</script>

php写文件的方法

实例一

 代码如下 复制代码
$filename = 'test.txt';
$filename = dirname ( __FILE__ ) . '/' . $filename;
if (file_exists ( $filename )) {
    if (! is_writable ( $filename )) {
        exit('is not writable');
    }
    $handle = fopen ( $filename, "a+b" );
    $content = 'this is test words';
    $content .= "n";
    fwrite($handle, $content);
    fclose ( $handle );
} else {
    exit('file is not exists');
}

实例二

 代码如下 复制代码

$filename = 'test.txt';
$filename = dirname ( __FILE__ ) . '/' . $filename;
if (file_exists ( $filename )) {
    if (! is_writable ( $filename )) {
        exit('is not writable');
    }
    $content = 'this is test words';
    $content .= "n";
    file_put_contents($filename, utf8_encode($content)); 
} else {
    exit('file is not exists');
}


php读取文件

实例一

 代码如下 复制代码

$filename = 'test.txt';
        $filename = dirname ( __FILE__ ) . '/' . $filename;
        if (file_exists ( $filename )) {
            if (! is_readable ( $filename )) {
                exit('is not readable');
            }
            $contents = file_get_contents($filename);
            $contents = explode("n", $contents);
            print_r($contents);
        } else {
            exit('file is not exists');
        }

实例二

 代码如下 复制代码

$filename = 'test.txt';
$filename = dirname ( __FILE__ ) . '/' . $filename;
if (file_exists ( $filename )) {
    if (! is_readable ( $filename )) {
        exit('is not readable');
    }
    $handle = fopen ( $filename, "rb" );
    $contents = fread($handle, filesize ($filename));
    //$contents = stream_get_contents($handle); // 也可以用方法替换上一行
    $contents = explode("n", $contents);
    fclose ( $handle );
    print_r($contents);
} else {
    exit('file is not exists');
}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn