Home php教程 php手册 PHP学习:文件操作

PHP学习:文件操作

Jun 06, 2016 pm 07:46 PM
php three study operate data document

将数据写或读入文件,基本上分为三个步骤: 1. 打开一个文件(如果存在) 2. 写 / 读文件 3. 关闭这个文件 l 打开文件 在打开文件文件之前,我们需要知道这个文件的路径,以及此文件是否存在。 用 $_SERVER[DOCUMENT_ROOT] 内置全局变量,来获得站点的相对路

将数据写或读入文件,基本上分为三个步骤:

1.         打开一个文件(如果存在)

2.         /读文件

3.         关闭这个文件

 

l打开文件

在打开文件文件之前,我们需要知道这个文件的路径,以及此文件是否存在。

 

$_SERVER[“DOCUMENT_ROOT”]内置全局变量,来获得站点的相对路径。如下:

$root = $_SERVER[“DOCUMENT_ROOT”];

 

在用函数file_exists()来检测文件是否存在。如下:

If(!file_exists("$root/order.txt")){echo ‘文件不存在’;}

 

接下来用fopen()函数打开这个文件。

$fp = fopen("$root/order.txt",'ab');

 

fopen()函数,接受2个或3个或4个参数。

第一个参数为文件路径,第二个为操作方式(读//追加等等),必选参数。

$fp = fopen("$root/order.txt",'ab');

 

第三个为可选参数,如果需要PHPinclude_path中搜索一个文件,就可以使用它,不需要提供目录名或路径。

$fp = fopen("order.txt",'ab',true);

 

第四个也为可选参数,允许文件名称以协议名称开始(如http://)并且在一个远程的位置打开这个文件,也支持一些其他的协议,比如ftp等等。

 

如果fopen()成功的打开一个文件,就返回一个指向此文件的指针。在上面我们保存到了$fp变量中。

 

附文件模式图

PHP学习:文件操作

l写文件

PHP中写文件比较简单。直接用fwrite()函数即可。

fwrite()的原型如下

int fwrite(resource handle,string string [,int length]);

 

第三个参数是可选的,表明写入文件的最大长度。

可以通过内置strlen()函数获得字符串的长度,如下:

fwrite($fp,$outputinfo,strlen($outputinfo));

 

此函数告诉PHP$outputinfo中的信息保存到$fp指向的文件中。

l读文件

1.以只读模式打开文件

仍然使用fopen()函数,但只读模式打开文件,就用“rb”文件模式。如下:

$fp = fopen(“$root/order.txt”,’rb’);

2.知道何时读完文件

我们用while循环来读取文件内容,用feof()函数,作为循环条件的终止条件。如下:

while(!feof($fp)){

         
//要处理的信息

}

3.每次读取一行记录

fgets()函数可以从文本文件中读取一行内容。如下:

$fp = fopen("$root/order.txt",'rb');

while(!feof($fp)){

         
$info = fgets($fp,999);

         
echo $info.'
';

}

fclose($fp);

 

这样,他将不断的读入数据,直到读取一个换行符(\n)或者文件结束符EOF,或者是从文件中读取了998B,可以读取的最大长度为指定的长度减去1B

4.读取整个文件

PHP提供了4中不同的方式来读取整个文件。

a).readfile()函数

         它可以不用先fopen($path)文件和关闭文件,也不用echo,直接使用即可。如下:        

 readfile(“$root/order.txt”);

         它会自动把文件的信息,输出到浏览器中。它的原型如下:         

Int readfile(string filename,[int use_include_path[,resource context]]);

         第二个可选参数指定了PHP是否在include_path中查找文件,这一点于fopen函数一样,返回值为从文件中读取的字节总数。

         注:直接使用,不用fopenfclose

b).fpassthru()函数

         要使用这个函数,必须先fopen()打开一个文件。然后将文件的指针作为参数传递给fpassthru(),这样就可以把文件指针所指向的文件内容输出。然后再将这个文件关闭。如下:         

$fp = fopen(“$root/order.txt”,'rb');
fpassthru($fp);
fclose($fp);

         返回值同样为从文件中读取的字节总数。

         注:必须fopenfclose

c).file()函数

         除了将文件输出到浏览器中外,他和readfile()函数是一样的,它把结果发送到一个数组中。如下:         

$fileArray = file(“$root/order.txt”);

         文件中的每一行,将作为数组的每一个元素。

         注:直接使用,不用fopenfclose

d).file_get_contents()函数

readfile()相同,但是该函数将以字符串的形式返回文件内容,而不是将文件内容直接输出到浏览器中,也就是必须使用echo 输出,如下:

echo file_get_contents(“$root/order.txt”);

注:直接使用,不用fopenfclose

5.读取一个字符

fgetc()函数从一个文件中一次读取一个字符,它具有一个文件指针函数,这也是唯一的参数,而且它返回下一个字符。如下:

$fp = fopen("$root/order.txt",'rb');

while(!feof($fp)){

         
$char = fgetc($fp);            

         
if(!feof($fp)){

                   
echo ($char == "\n" ? '
' : $char);

         }

}

fclose($fp);

注:fgetc()函数的一个缺点就是它返回文件的结束符EOF,而fgets()则不会。读取字符后还需要判断feof()

6. 读取任意长度

fread()函数即为从文件中读取任一长度的字节,函数原型如下:

string fread(resource fp,int length);

使用该函数时,它或者是读满了length参数所指定的字节数,或者是读到了文件的结束。

$fp = fopen("$root/order.txt",'rb');
echo fread($fp,10); //读取10个字节
fclose($fp);

l关闭文件

关闭文件比较简单,直接调用fclose()函数即可,如果返回true,则表明成功,反之。如下:

fclose($fp);

l删除文件

unlink()函数(没有名为delete的函数),如下:

unlink("$root/order.txt");

l确定文件大小

可以使用filesize()函数来查看一个文件的大小(字节为单位),如下: 

echo filesize("$root/order.txt");

 参考:PHP与MySQL.WEB开发

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 尊渡假赌尊渡假赌尊渡假赌

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
1664
14
PHP Tutorial
1268
29
C# Tutorial
1248
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

See all articles