検索
ホームページphp教程PHP源码php读取文件与写入文件方法实例

在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');
}

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

AtomエディタMac版ダウンロード

AtomエディタMac版ダウンロード

最も人気のあるオープンソースエディター

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強力な PHP 統合開発環境

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser は、オンライン試験を安全に受験するための安全なブラウザ環境です。このソフトウェアは、あらゆるコンピュータを安全なワークステーションに変えます。あらゆるユーティリティへのアクセスを制御し、学生が無許可のリソースを使用するのを防ぎます。

EditPlus 中国語クラック版

EditPlus 中国語クラック版

サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール