Home > Article > Backend Development > How to modify the content of txt file in php
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);".
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('文件存在');</script>"; } else { // echo "<script language=javascript>alert('文件不存在 $path');</script>"; } $cbody = file($path); //print_r($cbody); $wifissid=$cbody[0]; $wifipwd=$cbody[1]; $wifissid=str_replace('wifiSSID=','' ,$wifissid);//文本替换 将$wifissid值的wifiSSID替换为' ' $wifipwd=str_replace('wifiPWD=','' ,$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['wifissid']; $wifipwd2=$_POST['wifipwd']; $arr=array("wifiSSID=".$wifissid2,"\n","wifiPWD=".$wifipwd2); $fp=fopen($path, 'w'); 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!