recherche
Maisonphp教程php手册PHP 文件读取 fread、fgets、fgetc、file_get_contents 与 file 函数

fread()、fgets()、fgetc()、file_get_contents() 与 file() 函数用于从文件中读取内容。

 

fread()

fread() 函数用于读取文件(可安全用于二进制文件)。
语法:

<span style="color: #0000ff">string</span> <span style="color: #008080">fread</span>( int handle, int length )

fread() 从文件指针 handle 读取最多 length 个字节。当遇到下列任何一种情况时,会停止读取文件:

  • 在读取完最多 length 个字节数时
  • 达到文件末尾的时候(EOF)
  • (对于网络流)当一个包可用时
  • 或(在打开用户空间流之后)已读取了 8192 个字节时

从文件中读取 10 个字节(包括空格):

<span style="color: #000000">php
</span><span style="color: #008000">//</span><span style="color: #008000"> http://www.manongjc.com/article/1346.html</span>
<span style="color: #800080">$filename</span> = "test.txt"<span style="color: #000000">;
</span><span style="color: #800080">$fh</span> = <span style="color: #008080">fopen</span>(<span style="color: #800080">$filename</span>, "r"<span style="color: #000000">);
</span><span style="color: #0000ff">echo</span> <span style="color: #008080">fread</span>(<span style="color: #800080">$fh</span>, "10"<span style="color: #000000">);
</span><span style="color: #008080">fclose</span>(<span style="color: #800080">$fh</span><span style="color: #000000">);
</span>?>

提示

如果只是想将一个文件的内容读入到一个字符串中,应该用性能更好的 file_get_contents() 。

 

fgets()

fgets() 函数用于从文件中读取 一行 数据,并将文件指针指向下一行。
提示:如果想在读取的时候去掉文件中的 HTML 标记,请使用 fgetss() 函数。
语法:

<span style="color: #0000ff">string</span> <span style="color: #008080">fgets</span>( int handle [, int length] )

fgets() 从 handle 指向的文件中读取一行并返回长度最多为 length-1 字节的字符串。碰到换行符(包括在返回值中)、EOF 或者已经读取了 length-1 字节后停止。如果没有指定 length ,则默认为 1K ,或者说 1024 字节。
例子:

<span style="color: #000000">php
</span><span style="color: #800080">$fh</span> = @<span style="color: #008080">fopen</span>("test.txt","r") or <span style="color: #0000ff">die</span>("打开 test.txt 文件出错!"<span style="color: #000000">);
</span><span style="color: #008000">//</span><span style="color: #008000"> if条件避免无效指针
// http://www.manongjc.com/article/1347.html</span>
<span style="color: #0000ff">if</span>(<span style="color: #800080">$fh</span><span style="color: #000000">){
    </span><span style="color: #0000ff">while</span>(!<span style="color: #008080">feof</span>(<span style="color: #800080">$fh</span><span style="color: #000000">)) {
        </span><span style="color: #0000ff">echo</span> <span style="color: #008080">fgets</span>(<span style="color: #800080">$fh</span>), '<br>'<span style="color: #000000">;
    }
}
</span><span style="color: #008080">fclose</span>(<span style="color: #800080">$fh</span><span style="color: #000000">);
</span>?>

补充说明

feof() 函数测试文件指针是否到了文件结束的位置,该文件指针必须有效,如果是无效的资源,则会陷入无限循环中。参见《PHP 文件指针函数》

 

fgetc()

fgetc() 函数用于 逐字 读取文件数据,直到文件结束。
语法:

<span style="color: #0000ff">string</span> <span style="color: #008080">fgetc</span>( <span style="color: #0000ff">resource</span> handle )

例子:

<span style="color: #000000">php
</span><span style="color: #800080">$fh</span> = @<span style="color: #008080">fopen</span>("test.txt","r") or <span style="color: #0000ff">die</span>("打开 test.txt 文件出错!"<span style="color: #000000">);
</span><span style="color: #008000">//</span><span style="color: #008000"> http://www.manongjc.com/article/1348.html</span>
<span style="color: #0000ff">if</span>(<span style="color: #800080">$fh</span><span style="color: #000000">){
    </span><span style="color: #0000ff">while</span>(!<span style="color: #008080">feof</span>(<span style="color: #800080">$fh</span><span style="color: #000000">)) {
        </span><span style="color: #0000ff">echo</span> <span style="color: #008080">fgetc</span>(<span style="color: #800080">$fh</span><span style="color: #000000">);
    }
}
</span><span style="color: #008080">fclose</span>(<span style="color: #800080">$fh</span><span style="color: #000000">);
</span>?>

 

file_get_contents()

file_get_contents() 函数用于把 整个文件 读入一个字符串,成功返回一个字符串,失败则返回 FALSE。
语法:

<span style="color: #0000ff">string</span> <span style="color: #008080">file_get_contents</span>( <span style="color: #0000ff">string</span> filename [, int offset [, int maxlen]] )

参数说明:
参数    说明
filename    要读取的文件名称
offset    可选,指定读取开始的位置,默认为文件开始位置
maxlen    可选,指定读取文件的长度,单位字节
例子:

<span style="color: #000000">php
</span><span style="color: #008000">//</span><span style="color: #008000"> 读取时同事将换行符转换成 <br></span>
<span style="color: #0000ff">echo</span> <span style="color: #008080">nl2br</span>(<span style="color: #008080">file_get_contents</span>('test.txt'<span style="color: #000000">));
</span>?>

 

file()

file() 函数用于把 整个文件 读入一个数组中,数组中的每个单元都是文件中相应的一行,包括换行符在内。成功返回一个数组,失败则返回 FALSE。
语法:

<span style="color: #0000ff">array</span> <span style="color: #008080">file</span>( <span style="color: #0000ff">string</span> filename )

例子:

<span style="color: #000000">php
</span><span style="color: #800080">$lines</span> = <span style="color: #008080">file</span>('test.txt'<span style="color: #000000">);
</span><span style="color: #008000">//</span><span style="color: #008000"> 在数组中循环并加上行号
// http://www.manongjc.com/article/1349.html</span>
<span style="color: #0000ff">foreach</span> (<span style="color: #800080">$lines</span> <span style="color: #0000ff">as</span> <span style="color: #800080">$line_num</span> => <span style="color: #800080">$line</span><span style="color: #000000">) {
    </span><span style="color: #0000ff">echo</span> "Line #{<span style="color: #800080">$line_num</span>} : ",<span style="color: #800080">$line</span>,'<br>'<span style="color: #000000">;
}
</span>?>

test.txt 文件内容:
你好!
这是第二行文字。
浏览器显示:
Line #0 : 你好!
Line #1 : 这是第二行文字。

Déclaration
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

Video Face Swap

Video Face Swap

Échangez les visages dans n'importe quelle vidéo sans effort grâce à notre outil d'échange de visage AI entièrement gratuit !

Outils chauds

Listes Sec

Listes Sec

SecLists est le compagnon ultime du testeur de sécurité. Il s'agit d'une collection de différents types de listes fréquemment utilisées lors des évaluations de sécurité, le tout en un seul endroit. SecLists contribue à rendre les tests de sécurité plus efficaces et productifs en fournissant facilement toutes les listes dont un testeur de sécurité pourrait avoir besoin. Les types de listes incluent les noms d'utilisateur, les mots de passe, les URL, les charges utiles floues, les modèles de données sensibles, les shells Web, etc. Le testeur peut simplement extraire ce référentiel sur une nouvelle machine de test et il aura accès à tous les types de listes dont il a besoin.

mPDF

mPDF

mPDF est une bibliothèque PHP qui peut générer des fichiers PDF à partir de HTML encodé en UTF-8. L'auteur original, Ian Back, a écrit mPDF pour générer des fichiers PDF « à la volée » depuis son site Web et gérer différentes langues. Il est plus lent et produit des fichiers plus volumineux lors de l'utilisation de polices Unicode que les scripts originaux comme HTML2FPDF, mais prend en charge les styles CSS, etc. et présente de nombreuses améliorations. Prend en charge presque toutes les langues, y compris RTL (arabe et hébreu) ​​et CJK (chinois, japonais et coréen). Prend en charge les éléments imbriqués au niveau du bloc (tels que P, DIV),

SublimeText3 Linux nouvelle version

SublimeText3 Linux nouvelle version

Dernière version de SublimeText3 Linux

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

DVWA

DVWA

Damn Vulnerable Web App (DVWA) est une application Web PHP/MySQL très vulnérable. Ses principaux objectifs sont d'aider les professionnels de la sécurité à tester leurs compétences et leurs outils dans un environnement juridique, d'aider les développeurs Web à mieux comprendre le processus de sécurisation des applications Web et d'aider les enseignants/étudiants à enseigner/apprendre dans un environnement de classe. Application Web sécurité. L'objectif de DVWA est de mettre en pratique certaines des vulnérabilités Web les plus courantes via une interface simple et directe, avec différents degrés de difficulté. Veuillez noter que ce logiciel