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

How to modify the content of txt file in php

藏色散人
藏色散人Original
2021-10-15 09:43:475421browse

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);

//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);

//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);

// 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);

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!

Statement:
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