A. php写入数据到php文件第2行 以及更改第3行数据 会的来
下面是完整的代码:
//根据你的PHP设置自已可以把<?php替换为<?
<?php
//要更改的php文件
$filename = 'id.php';
//要插入的内容
$addContent = "wole\n";
//要更改的内容
$updateContent="qwe\n";
// 确定文件存在并且可写。
if (is_writable($filename)) {
// 将文件读入数组,每行是一条记录
$lines = file ($filename);
// 使用写入方式打开打开$filename,文件指针将会在文件的开头
if (!$handle = fopen($filename, 'w')) {
print "不能打开文件 $filename";
exit;
}
//在数组中循环,当到达第2行时插入新的内容。
foreach ($lines as $line_num => $line) {
if($line_num==1){
//将$addContent写入到文件中。
if (!fwrite($handle, $addContent)) {
print "不能写入到文件 $filename";
exit;
}
}
//写入原来的行内容到文件中
if (!fwrite($handle, $line)) {
print "不能写入到文件 $filename";
exit;
}
}
//更改数据第3行zxcv为qwe,把上面foreach注释掉,打开下面注释掉的代码
// foreach ($lines as $line_num => $line) {
// if($line_num==2){
// //将$updateContent写入到文件中。
// if (!fwrite($handle, $updateContent)) {
// print "不能写入到文件 $filename";
// exit;
// }
// }
// else{
// //写入原来的行内容到文件中
// if (!fwrite($handle, $line)) {
// print "不能写入到文件 $filename";
// exit;
// }
// }
// }
fclose($handle);
} else {
print "文件 $filename 不可写";
}
?>
B. php将数组元素按行写入文本文件
<?php
$arr=array('aa','bb','cc');
$str=implode(" ",$arr);
file_put_contents("A.txt",$str);
?>