Table of Contents
1.fread
2.fgets
3.fgetss
4.file
6.file_get_contents
8.parse_ini_file
Home php教程 php手册 PHP读取文件的常见方法

PHP读取文件的常见方法

Jun 14, 2016 am 12:02 AM
php code Open source document programming programming language read software development

整理了一下PHP中读取文件的几个方法,方便以后查阅。

1.fread

  string fread ( int $handle , int $length )

  fread() 从 handle 指向的文件中读取最多 length 个字节。该函数在读取完最多 length 个字节数,或到达 EOF 的时候,或(对于网络流)当一个包可用时,或(在打开用户空间流之后)已读取了 8192 个字节时就会停止读取文件,视乎先碰到哪种情况。

  fread() 返回所读取的字符串,如果出错返回 FALSE。

<?php <br>    <span style="color: #800080;">$filename</span> = "/usr/local/something.txt";<br>    <span style="color: #800080;">$handle</span> = <span style="color: #008080;">fopen</span>(<span style="color: #800080;">$filename</span>, "r");<span style="color: #008000;">//</span><span style="color: #008000;">读取二进制文件时,需要将第二个参数设置成'rb'<br>    <br>    //通过filesize获得文件大小,将整个文件一下子读到一个字符串中</span><span style="color: #008000;"><br></span>    <span style="color: #800080;">$contents</span> = <span style="color: #008080;">fread</span>(<span style="color: #800080;">$handle</span>, <span style="color: #008080;">filesize</span> (<span style="color: #800080;">$filename</span>));<br>    <span style="color: #008080;">fclose</span>(<span style="color: #800080;">$handle</span>);<br>?>
Copy after login


  如果所要读取的文件不是本地普通文件,而是远程文件或者流文件,就不能用这种方法,因为,filesize不能获得这些文件的大小。此时,你需要通过feof()或者fread()的返回值判断是否已经读取到了文件的末尾。

  例如:

<?php <br>    <span style="color: #800080;">$handle</span> = <span style="color: #008080;">fopen</span>('http://www.baidu.com', 'r');<br>    <span style="color: #800080;">$content</span> = '';<br>    <span style="color: #0000ff;">while</span>(!<span style="color: #008080;">feof</span>(<span style="color: #800080;">$handle</span>)){<br>        <span style="color: #800080;">$content</span> .= <span style="color: #008080;">fread</span>(<span style="color: #800080;">$handle</span>, 8080);<br>    }<br>    <span style="color: #0000ff;">echo</span> <span style="color: #800080;">$content</span>;<br>    <span style="color: #008080;">fclose</span>(<span style="color: #800080;">$handle</span>);<br>?>
Copy after login

或者:

<?php <br>    <span style="color: #800080;">$handle</span> = <span style="color: #008080;">fopen</span>('http://www.baidu.com', 'r');<br>    <span style="color: #800080;">$content</span> = '';<br>    <span style="color: #0000ff;">while</span>(<span style="color: #0000ff;">false</span> != (<span style="color: #800080;">$a</span> = <span style="color: #008080;">fread</span>(<span style="color: #800080;">$handle</span>, 8080))){<span style="color: #008000;">//</span><span style="color: #008000;">返回false表示已经读取到文件末尾</span><span style="color: #008000;"><br></span>        <span style="color: #800080;">$content</span> .= <span style="color: #800080;">$a</span>;<br>    }<br>    <span style="color: #0000ff;">echo</span> <span style="color: #800080;">$content</span>;<br>    <span style="color: #008080;">fclose</span>(<span style="color: #800080;">$handle</span>);<br>?>
Copy after login

 

2.fgets

  string fgets ( int $handle [, int $length ] )

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

<?php <br>    <span style="color: #800080;">$handle</span> = <span style="color: #008080;">fopen</span>('./file.txt', 'r');<br>    <span style="color: #0000ff;">while</span>(!<span style="color: #008080;">feof</span>(<span style="color: #800080;">$handle</span>)){<br>        <span style="color: #0000ff;">echo</span> <span style="color: #008080;">fgets</span>(<span style="color: #800080;">$handle</span>, 1024);<br>    }<br>    <span style="color: #008080;">fclose</span>(<span style="color: #800080;">$handle</span>);<br>?>
Copy after login

  Note: length 参数从 PHP 4.2.0 起成为可选项,如果忽略,则行的长度被假定为 1024。从 PHP 4.3 开始,忽略掉 length 将继续从流中读取数据直到行结束。如果文件中的大多数行都大于 8KB,则在脚本中指定最大行的长度在利用资源上更为有效。从 PHP 4.3 开始本函数可以安全用于二进制文件。早期的版本则不行。

3.fgetss

  string fgetss ( resource $handle [, int $length [, string $allowable_tags ]] )

  跟fgets功能一样,但是fgetss会尝试从读取的文本中去掉任何 HTML 和 PHP 标记,可以用可选的第三个参数指定哪些标记不被去掉。

<?php <br>    <span style="color: #800080;">$handle</span> = <span style="color: #008080;">fopen</span>('./file.txt', 'r');<br>    <span style="color: #0000ff;">while</span>(!<span style="color: #008080;">feof</span>(<span style="color: #800080;">$handle</span>)){<br>        <span style="color: #0000ff;">echo</span> <span style="color: #008080;">fgetss</span>(<span style="color: #800080;">$handle</span>, 1024, '<br>');<br>    }<br>    <span style="color: #008080;">fclose</span>(<span style="color: #800080;">$handle</span>);<br>?>
Copy after login

 

4.file

  array file ( string $filename [, int $use_include_path [, resource $context ]] )
  将文件内容读入一个数组中,数组的每一项对应文件中的一行,包括换行符在内。不需要行结束符时可以使用 rtrim() 函数过滤换行符。

<?php <br>    <span style="color: #800080;">$a</span> = <span style="color: #008080;">file</span>('./file.txt');<br>    <span style="color: #0000ff;">foreach</span>(<span style="color: #800080;">$a</span> <span style="color: #0000ff;">as</span> <span style="color: #800080;">$line</span> => <span style="color: #800080;">$content</span>){<br>        <span style="color: #0000ff;">echo</span> 'line '.(<span style="color: #800080;">$line</span> + 1).':'.<span style="color: #800080;">$content</span>;<br>    }<br>?>
Copy after login


 5.readfile

  int readfile ( string $filename [, bool $use_include_path [, resource $context ]] )

  读入一个文件并写入到输出缓冲。返回从文件中读入的字节数。如果出错返回 FALSE 并且除非是以 @readfile() 形式调用,否则会显示错误信息。

<?php <br>    <span style="color: #800080;">$size</span> = <span style="color: #008080;">readfile</span>('./file.txt');<br>    <span style="color: #0000ff;">echo</span> <span style="color: #800080;">$size</span>;<br>?>
Copy after login

 

6.file_get_contents

  string file_get_contents ( string $filename [, bool $use_include_path [, resource $context [, int $offset [, int $maxlen ]]]] )

  将文件读入一个字符串。第三个参数$context可以用来设置一些参数,比如访问远程文件时,设置超时等等。

  另外,file_get_contents相对于以上几个函数,性能要好得多,所以应该优先考虑使用file_get_contents。但是readfile貌似比file_get_contents性能好一点(?),因为它不需要调用fopen。

<?php <br>    <span style="color: #800080;">$ctx</span> = <span style="color: #008080;">stream_context_create</span>(<span style="color: #0000ff;">array</span>( <br>        'http' => <span style="color: #0000ff;">array</span>( <br>            'timeout' => 1    <span style="color: #008000;">//</span><span style="color: #008000;">设置超时</span><span style="color: #008000;"><br></span>            ) <br>        ) <br>    ); <br>    <span style="color: #0000ff;">echo</span> <span style="color: #008080;">file_get_contents</span>("http://www.baidu.com/", 0, <span style="color: #800080;">$ctx</span>); <br>?>
Copy after login


7.fpassthru

   int fpassthru ( resource $handle )

  将给定的文件指针从当前的位置读取到 EOF 并把结果写到输出缓冲区。

<?php <br>    <span style="color: #008080;">header</span>("Content-Type:text/html;charset=utf-8"); <br>    <span style="color: #800080;">$handle</span> = <span style="color: #008080;">fopen</span>('./test2.php', 'r');<br>    <span style="color: #008080;">fseek</span>(<span style="color: #800080;">$handle</span>, 1024);<span style="color: #008000;">//</span><span style="color: #008000;">将指针定位到1024字节处</span><span style="color: #008000;"><br></span>    <span style="color: #008080;">fpassthru</span>(<span style="color: #800080;">$handle</span>);<br>?>
Copy after login

 

8.parse_ini_file

  array parse_ini_file ( string $filename [, bool $process_sections ] )

  parse_ini_file() 载入一个由 filename 指定的 ini 文件,并将其中的设置作为一个联合数组返回。如果将最后的 process_sections 参数设为 TRUE,将得到一个多维数组,包括了配置文件中每一节的名称和设置。process_sections 的默认值是 FALSE。

  注意:

1. 如果 ini 文件中的值包含任何非字母数字的字符,需要将其括在双引号中(")。
2. 有些保留字不能作为 ini 文件中的键名,包括:null,yes,no,true 和 false。值为 null,no 和 false 等效于 "",值为 yes 和 true 等效于 "1"。字符 {}|&~![()" 也不能用在键名的任何地方,而且这些字符在选项值中有着特殊的意义。

test.ini文件内容:

; This is a sample configuration <span style="color: #008080;">file</span><br>; Comments start with ';', <span style="color: #0000ff;">as</span> in php.ini<br><br>[first_section]<br>one = 1<br>five = 5<br>animal = BIRD<br><br>[second_section]<br>path = "/usr/local/bin"<br>URL = "http://www.example.com/~username
Copy after login

test.php内容:

<?php <br>    <span style="color: #800080;">$config</span> = <span style="color: #008080;">parse_ini_file</span>('./test.ini', ture);<br>    <span style="color: #008080;">print_r</span>(<span style="color: #800080;">$config</span>);<br>?>
Copy after login

输出内容:

Array<br>(<br>    [first_section] => Array<br>        (<br>            [one] => 1<br>            [five] => 5<br>            [animal] => BIRD<br>        )<br><br>    [second_section] => Array<br>        (<br>            [path] => /usr/local/bin<br>            [URL] => http://www.example.com/~username<br>        )<br><br>)
Copy after login

 

 

 

几个注意事项:

  1. 鼓励在处理二进制文件时使用 b 标志,即使系统并不需要,这样可以使脚本的移植性更好。 

  2. allow_url_fopen选项激活了 URL 形式的 fopen 封装协议使得可以访问 URL 对象例如文件。默认的封装协议提供用 ftp 和 http 协议来访问远程文件,一些扩展库例如 zlib 可能会注册更多的封装协议。出于安全性考虑,此选项只能在 php.ini 中设置。

  3. 如果要打开有特殊字符的 URL (比如说有空格),就需要使用 urlencode() 进行 URL 编码。

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

See all articles