Home > Backend Development > PHP Problem > How to modify the content of txt file in php

How to modify the content of txt file in php

藏色散人
Release: 2023-03-13 10:10:02
Original
5521 people have browsed it

How to modify the content of the txt file in php: 1. Create a PHP sample file; 2. Open the file through fopen; 3. Modify the content of the txt file through "fwrite($fp,$password);".

How to modify the content of txt file in php

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

How to modify the content of txt file with php?

php Read and modify txt file

//There is only one line of data in the txt file Read

$fp = fopen("password.txt", "r");
if($fp)
{
     $pwd = fgets($fp);
}
else
{
     echo "打开文件失败";
}
fclose($fp);
Copy after login

//txt file There is only one line of data in the file

$fp = fopen("password.txt", "w");//文件被清空后再写入
if($fp)
{
     $flag=fwrite($fp,$password);
     if(!$flag)
     {
          echo "写入文件失败<br>";
          break;
     }
}
fclose($fp);
Copy after login

//txt file. There are multiple lines of data in the file and read in the form of an array

$path="wifi_customer_settings.txt";
$body = file_get_contents($path);
if( file_exists( $path ) )
{
    $body = file_get_contents($path);//转为数组
//echo "<script language=javascript>alert(&#39;文件存在&#39;);</script>";
}
else
{
   // echo "<script language=javascript>alert(&#39;文件不存在 $path&#39;);</script>";
}
$cbody = file($path);
//print_r($cbody);
$wifissid=$cbody[0];
$wifipwd=$cbody[1];
$wifissid=str_replace(&#39;wifiSSID=&#39;,&#39;&#39; ,$wifissid);//文本替换 将$wifissid值的wifiSSID替换为&#39; &#39;
$wifipwd=str_replace(&#39;wifiPWD=&#39;,&#39;&#39; ,$wifipwd);
Copy after login

// There are multiple lines of data in the txt file. Write in the form of an array.

$path="wifi_customer_settings.txt";
$wifissid2=$_POST[&#39;wifissid&#39;];
$wifipwd2=$_POST[&#39;wifipwd&#39;];
$arr=array("wifiSSID=".$wifissid2,"\n","wifiPWD=".$wifipwd2);
$fp=fopen($path, &#39;w&#39;);
fputs($fp,$arr[0]);
fputs($fp,$arr[1]);
fputs($fp,$arr[2]);
fclose($fp);
Copy after login

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to modify the content of txt file in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template