① php函数fwrite()的用法
在使用fopen函数打开文件时,你应该使用“a”模式来追加内容,而不是覆盖原有内容。这里有一个例子:
$f = fopen("a.txt","a");
接下来,使用fwrite函数写入内容“asd”时,将会追加到文件末尾,而不是替换原有的内容。这确保了文件中原有的内容不会被删除,而是保持不变。
如果你希望在文件开头插入新内容,可以先读取文件内容,然后将新内容和原有内容拼接起来,最后再次使用fwrite函数将整个字符串写入文件。例如:
$f = fopen("a.txt","r");
$content = fread($f,filesize("a.txt"));
fclose($f);
$newContent = "new content";
$fullContent = $newContent . $content;
$f = fopen("a.txt","w");
fwrite($f,$fullContent);
fclose($f);
这样操作后,文件将会从头开始包含你指定的新内容,原有的内容仍然会保留。
值得注意的是,如果你想要完全替换文件中的内容,可以使用“w”模式打开文件,然后使用fwrite函数写入新的内容。例如:
$f = fopen("a.txt","w");
fwrite($f,"new content");
fclose($f);
这样操作后,文件将仅包含你写入的新内容,原有的内容将被删除。
以上是fwrite函数的一些使用技巧,希望对你有所帮助。
② php创建文件夹并写入txt文件
php创建文件夹和写入文件:
$path="D:/test/";
if(!is_dir($path)){
mkdir($path,0777);//创建文件夹test,并给777的权限(所有权限)
}
$content="abc";//写入的内容
$file=$path."test.txt";//写入的文件
file_put_contents($file,$content,FILE_APPEND);//最简单的快速的以追加的方式写入写入方法,
③ php怎样把一个数组写入一个文件
请看代码吧:
<?php
//假如有数组$a,讲数组$a写入文件a.txt
$a=array(
"aa"=>123,
"bb"=>456
);
//将数组编程字符串的样式
$aString='$a='.var_export($a,true).';';
//写入文件
file_put_content(__DIR__.'/a.txt',$aString);
如果不明白的话,可以单独查看以上PHP函数的说明。
④ 如何用php向txt写入数据
/*先取出*/
$string = file_get_contents("1.txt");
$newstring; // 新数据
if (empty($string)) {
$string = $newstring;
} else {
$string .= '|' . $newstring;
}
file_put_contents("1.txt", $string);
⑤ php 如何创建txt文件
看手册,文件操作部分,比如 file_put_contents 就能满足要求
<?php
$file='people.txt';
//Thenewpersontoaddtothefile
$person="JohnSmith ";
//Writethecontentstothefile,
//usingtheFILE_
//andtheLOCK_
file_put_contents($file,$person,FILE_APPEND|LOCK_EX);
?>
⑥ php向txt内写入内容 怎么操作呢 这样操作会重新生成一个文本 内容就覆盖掉了 我想写入的时候换行 下次再换
<html>
<body>
<form action="" method="post">
输入内容:<input type="text" name="var">
<input type="submit" value="提交">
</form>
<?php
$text = "\r\n"$_POST['var'];
$f=fopen("aa.txt","a");
flock($f,LOCK_EX);
fputs($f,$text);
fclose($f);
?>
</body>
</html>
⑦ 用PHP,怎么修改txt文本内的内容
<?php
header("Content-type:text/html;charset=gbk");
if(isset($_POST['submit'])){
$editContent=$_POST['editContent'];//获取输入框的内容
$res=file_put_contents("test.txt",$editContent);//执行修改
if($res){
echo'内容修改成功!';
}else{
echo'内容修改失败!';
}
}else{
echo'请做出修改....';
}
?>
<formmethod="post"action="">
<textareaname="editContent"cols="100"rows="15">
<?phpechofile_get_contents("test.txt")?>
</textarea>
<buttonname="submit">确认</button>
</form>
⑧ php将数组元素按行写入文本文件
<?php
$arr=array('aa','bb','cc');
$str=implode(" ",$arr);
file_put_contents("A.txt",$str);
?>