Home php教程 PHP源码 php 常用文件操作学习笔记

php 常用文件操作学习笔记

Jun 08, 2016 pm 05:23 PM
array file fopen handler nbsp

在php中如果你要对文件进行一些操作是很方便的事情了,因为php提供了大量的php文件操作函数,下面我来给大家总结一下php文件操作方法与函数。

<script>ec(2);</script>

1、获取文件名:basename();

2、获取文件所在的目录:dirname();

3、pathinfo()获取文件信息,返回结果为一个array,包括路径、文件全名、文件名和扩展名。例如:

 代码如下 复制代码

$file = '/com/netingcn/error.log';
print_r(pathinfo($file));

结果为:

Array(
    [dirname] => /com/netingcn
    [basename] => error.log
    [extension] => log
    [filename] => error
)

4、判断文件是否存在:is_file();

5、判断目录是否存在:is_dir();

6、判断文件或目录是否存在:file_exists();

7、读取文件所有内容:file()或file_get_contents(),其中file()返回的是一个一行为元素的array,file_get_contents()把文件全部内容作为一个String返回;

8、写文件fwrite,如:

 代码如下 复制代码

$handler = fopen($file, 'w'); // w 会冲掉以前的内容、a 是追加
fwrite($handler, 'content');
fclose($handler);              //记得关闭打开的文件句柄9、文件读取操作有很多,下面简单介绍几个:

$handler = fopen($file, 'r');

while(!feof($handler)) {
    $datas[] = fgets($handler);  //读取一行内容
}

while(!feof($handler)) {
    $datas[] = fgetss($handler); //读取一行内容并过来html标记
}

while(!feof($handler)) {
    $datas[] = fgetcsv($handler); //读取一行内容并解析csv字段
}

$content = fread($handler, $strLength); //读取指定长读的字符

fclose($handler);


 PHP 读文件内容,此文件为txt,路径$filePath为'list.txt', 即放在和php文件同一个目录,

    注意:

          本人的txt的内容样式如下:

                  Email,FirstName,LastName...

                  neil@ddd.com,neil,zhou...

                  ...

具体实现根据自身情况修改。

 代码如下 复制代码

    $fp = fopen($filePath,"r ");
    $a = read_content_to_array($fp);   // 取得文本文件中的内容
    fclose($fp);

 

/**
    @desc read file content to array
    @params $fp: file resource
    @return array
*/
function read_content_to_array($fp){
    $i=0;
    $a = array();
    while (!feof ($fp)) {            //while循环,条件:没到文件的末端。


        $buffer = fgets($fp, MAX_BYTES_PER_ROW);  //fgets() 函数用于从文件中逐行读取文件,,读取的字节数。默认是 1024 字节。MAX_BYTES_PER_ROW为自定义的一个常量,读取的字节数


        $block=explode(STR_TD_DIVIDER,$buffer); //用分隔符对操作的一行($buffer)进行分割,返回由字符串组成的数组。STR_TD_DIVIDER为自定义的一个常量,每行中各个字段之间的分隔符。


        $a[$i]=$block;
        $i=$i+1;                     //通过while循环,带动i值递增,实现数组构建。
    }
    return $a;
}

 

PHP 写内容到txt文件中

 代码如下 复制代码

$handle = fopen($filePath, "w ");
fwrite($handle,$str);
fclose($handle);

怎么样,是不是看起来很简单呢?下面是一些简单知识的总结:

fopen()
fopen() 函数用于在 PHP 中打开文件,此函数的第一个参数含有要打开的文件的名称,第二个参数规定了使用哪种模式来打开文件.

模式      描述
r         只读。在文件的开头开始。
r+        读/写。在文件的开头开始。
w         只写。打开并清空文件的内容;如果文件不存在,则创建新文件。
w+        读/写。打开并清空文件的内容;如果文件不存在,则创建新文件。
a         追加。打开并向文件文件的末端进行写操作,如果文件不存在,则创建新文件。
a+        读/追加。通过向文件末端写内容,来保持文件内容。
x         只写。创建新文件。如果文件以存在,则返回 FALSE。
x+        读/写。创建新文件。如果文件已存在,则返回 FALSE 和一个错误。
注释:如果 fopen() 无法打开指定文件,则返回 0 (false)。


feof()
检测 End-of-file
feof() 函数检测是否已达到文件的末端 (EOF),在循环遍历未知长度的数据时,feof() 函数很有用。注释:在 w 、a 以及 x 模式,您无法读取打开的文件!
if (feof($file)) echo "End of file";
 
fgets()
fgets() 函数用于从文件中逐行读取文件。在调用该函数之后,文件指针会移动到下一行。

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 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
1663
14
PHP Tutorial
1264
29
C# Tutorial
1237
24
Solution: Your organization requires you to change your PIN Solution: Your organization requires you to change your PIN Oct 04, 2023 pm 05:45 PM

The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

How to adjust window border settings on Windows 11: Change color and size How to adjust window border settings on Windows 11: Change color and size Sep 22, 2023 am 11:37 AM

Windows 11 brings fresh and elegant design to the forefront; the modern interface allows you to personalize and change the finest details, such as window borders. In this guide, we'll discuss step-by-step instructions to help you create an environment that reflects your style in the Windows operating system. How to change window border settings? Press + to open the Settings app. WindowsI go to Personalization and click Color Settings. Color Change Window Borders Settings Window 11" Width="643" Height="500" > Find the Show accent color on title bar and window borders option, and toggle the switch next to it. To display accent colors on the Start menu and taskbar To display the theme color on the Start menu and taskbar, turn on Show theme on the Start menu and taskbar

How to change title bar color on Windows 11? How to change title bar color on Windows 11? Sep 14, 2023 pm 03:33 PM

By default, the title bar color on Windows 11 depends on the dark/light theme you choose. However, you can change it to any color you want. In this guide, we'll discuss step-by-step instructions for three ways to change it and personalize your desktop experience to make it visually appealing. Is it possible to change the title bar color of active and inactive windows? Yes, you can change the title bar color of active windows using the Settings app, or you can change the title bar color of inactive windows using Registry Editor. To learn these steps, go to the next section. How to change title bar color in Windows 11? 1. Using the Settings app press + to open the settings window. WindowsI go to "Personalization" and then

How to enable or disable taskbar thumbnail previews on Windows 11 How to enable or disable taskbar thumbnail previews on Windows 11 Sep 15, 2023 pm 03:57 PM

Taskbar thumbnails can be fun, but they can also be distracting or annoying. Considering how often you hover over this area, you may have inadvertently closed important windows a few times. Another disadvantage is that it uses more system resources, so if you've been looking for a way to be more resource efficient, we'll show you how to disable it. However, if your hardware specs can handle it and you like the preview, you can enable it. How to enable taskbar thumbnail preview in Windows 11? 1. Using the Settings app tap the key and click Settings. Windows click System and select About. Click Advanced system settings. Navigate to the Advanced tab and select Settings under Performance. Select "Visual Effects"

OOBELANGUAGE Error Problems in Windows 11/10 Repair OOBELANGUAGE Error Problems in Windows 11/10 Repair Jul 16, 2023 pm 03:29 PM

Do you see "A problem occurred" along with the "OOBELANGUAGE" statement on the Windows Installer page? The installation of Windows sometimes stops due to such errors. OOBE means out-of-the-box experience. As the error message indicates, this is an issue related to OOBE language selection. There is nothing to worry about, you can solve this problem with nifty registry editing from the OOBE screen itself. Quick Fix – 1. Click the “Retry” button at the bottom of the OOBE app. This will continue the process without further hiccups. 2. Use the power button to force shut down the system. After the system restarts, OOBE should continue. 3. Disconnect the system from the Internet. Complete all aspects of OOBE in offline mode

Display scaling guide on Windows 11 Display scaling guide on Windows 11 Sep 19, 2023 pm 06:45 PM

We all have different preferences when it comes to display scaling on Windows 11. Some people like big icons, some like small icons. However, we all agree that having the right scaling is important. Poor font scaling or over-scaling of images can be a real productivity killer when working, so you need to know how to customize it to get the most out of your system's capabilities. Advantages of Custom Zoom: This is a useful feature for people who have difficulty reading text on the screen. It helps you see more on the screen at one time. You can create custom extension profiles that apply only to certain monitors and applications. Can help improve the performance of low-end hardware. It gives you more control over what's on your screen. How to use Windows 11

10 Ways to Adjust Brightness on Windows 11 10 Ways to Adjust Brightness on Windows 11 Dec 18, 2023 pm 02:21 PM

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible

How to Fix Activation Error Code 0xc004f069 in Windows Server How to Fix Activation Error Code 0xc004f069 in Windows Server Jul 22, 2023 am 09:49 AM

The activation process on Windows sometimes takes a sudden turn to display an error message containing this error code 0xc004f069. Although the activation process is online, some older systems running Windows Server may experience this issue. Go through these initial checks, and if they don't help you activate your system, jump to the main solution to resolve the issue. Workaround – close the error message and activation window. Then restart the computer. Retry the Windows activation process from scratch again. Fix 1 – Activate from Terminal Activate Windows Server Edition system from cmd terminal. Stage – 1 Check Windows Server Version You have to check which type of W you are using

See all articles