Home Backend Development PHP Tutorial PHP创建文件,并向文件中写入数据,覆盖,追加的实现代码_PHP

PHP创建文件,并向文件中写入数据,覆盖,追加的实现代码_PHP

May 28, 2016 am 11:47 AM

创建文件我们用到函数

fopen ( string filename, string mode )
参数filename为创建文件名
参数mode为以什么方式打开文件filename
其中mode可能值列表:

mode 说明

‘r' 只读方式打开,将文件指针指向文件头。
‘r+' 读写方式打开,将文件指针指向文件头。
‘w' 写入方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。
‘w+' 读写方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。
‘a' 写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。
‘a+' 读写方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。
‘x' 创建并以写入方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。这和给 底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。此选项被 PHP 4.3.2 以及以后的版本所支持,仅能用于本地文件。
‘x+' 创建并以读写方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。这和给 底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。此选项被 PHP 4.3.2 以及以后的版本所支持,仅能用于本地文件。
下面代码是我通过利用函数fopen创建一个名为Demo,格式为txt的文件,并在文件中写入"Welcome To ItCodeWorld!"的数据。

< &#63;php
//要创建的两个文件
$TxtFileName = "Demo.txt";
//以读写方式打写指定文件,如果文件不存则创建
if( ($TxtRes=fopen ($TxtFileName,"w+")) === FALSE){
echo("创建可写文件:".$TxtFileName."失败");
exit();
}
echo ("创建可写文件".$TxtFileName."成功!</br>");
$StrConents = "Welcome To ItCodeWorld!";//要 写进文件的内容
if(!fwrite ($TxtRes,$StrConents)){ //将信息写入文件
echo ("尝试向文件".$TxtFileName."写入".$StrConents."失败!");
fclose($TxtRes);
exit();
}
echo ("尝试向文件".$TxtFileName."写入".$StrConents."成功!");
fclose ($TxtRes); //关闭指针
&#63;>
Copy after login

PHP 创建文件 – fopen()
fopen() 函数也用于创建文件。也许有点混乱,但是在 PHP 中,创建文件所用的函数与打开文件的相同。
如果您用 fopen() 打开并不存在的文件,此函数会创建文件,假定文件被打开为写入(w)或增加(a)。
下面的例子创建名为 "testfile.txt" 的新文件。此文件将被创建于 PHP 代码所在的相同目录中:
实例
$myfile = fopen("testfile.txt", "w")
PHP 文件权限
如果您试图运行这段代码时发生错误,请检查您是否有向硬盘写入信息的 PHP 文件访问权限。
PHP 写入文件 – fwrite()
fwrite() 函数用于写入文件。
fwrite() 的第一个参数包含要写入的文件的文件名,第二个参数是被写的字符串。
下面的例子把姓名写入名为 "newfile.txt" 的新文件中:
实例

<&#63;php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Bill Gates\n";
fwrite($myfile, $txt);
$txt = "Steve Jobs\n";
fwrite($myfile, $txt);
fclose($myfile);
&#63;>
Copy after login

请注意,我们向文件 "newfile.txt" 写了两次。在每次我们向文件写入时,在我们发送的字符串 $txt 中,第一次包含 "Bill Gates",第二次包含 "Steve Jobs"。在写入完成后,我们使用 fclose() 函数来关闭文件。
如果我们打开 "newfile.txt" 文件,它应该是这样的:
Bill Gates
Steve Jobs

PHP 覆盖(Overwriting)

如果现在 "newfile.txt" 包含了一些数据,我们可以展示在写入已有文件时发生的的事情。所有已存在的数据会被擦除并以一个新文件开始。
在下面的例子中,我们打开一个已存在的文件 "newfile.txt",并向其中写入了一些新数据:
实例

<&#63;php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Mickey Mouse\n";
fwrite($myfile, $txt);
$txt = "Minnie Mouse\n";
fwrite($myfile, $txt);
fclose($myfile);
&#63;>
Copy after login

如果现在我们打开这个 “newfile.txt” 文件,Bill 和 Steve 都已消失,只剩下我们刚写入的数据:

Mickey Mouse
Minnie Mouse


换行符‘\n'和回车符‘\r'
顾名思义,换行符就是另起一行,回车符就是回到一行的开头,所以我们平时编写文件的回车符应该确切来说叫做回车换行符

‘\n' 10 换行(newline)
‘\r' 13 回车(return)

也可以表示为'\x0a'和'\x0d'.(16进制)
在windows系统下,回车换行符号是”\r\n”.但是在Linux等系统下是没有”\r”符号的。
在解析文本或其他格式的文件内容时,常常要碰到判定回车换行的地方,这个时候就要注意既要判定”\r\n”又要判定”\n”。
写程序时可能得到一行,将其进行trim掉'\r',这样能得到你所需要的string了。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 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)

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

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,

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

What exactly is the non-blocking feature of ReactPHP? How to handle its blocking I/O operations? What exactly is the non-blocking feature of ReactPHP? How to handle its blocking I/O operations? Apr 01, 2025 pm 03:09 PM

An official introduction to the non-blocking feature of ReactPHP in-depth interpretation of ReactPHP's non-blocking feature has aroused many developers' questions: "ReactPHPisnon-blockingbydefault...

See all articles