如何在 PHP 中将字符串写入文本文件?
我想要像这样写入字符串:
1,hello,world!
2,welcome
然后把这两行放到文件中。如何在 PHP 中将字符串写入文本文件?
我想要像这样写入字符串:
1,hello,world!
2,welcome
然后把这两行放到文件中。写入txt文件:
<?php
$file = 'file.txt';
$data = 'this is your string to write';
file_put_contents($file, $data);
?>
要在页面上某个位置输出该文件的内容(请记住,页面必须具有 .php 扩展名才能使 PHP 生效):
<?php
// place this piece of code wherever you want the file contents to appear
readfile('file.txt');
?>
编辑:
回答你在评论中提出的另一个问题:
当将数据保存到文件时,原始代码是可以的,只需使用它即可。 不同的代码出现在从文件中输出内容时,因此现在它会像这样显示:
<?php
$contents = file_get_contents('file.txt');
$contents = explode("\n", $contents);
foreach($contents as $line){
$firstComma = (strpos($line, ","))+1;
$newLine = substr($line, $firstComma);
echo $newLine."\n";
}
?>
就这样试试吧。我这里没有我的服务器,所以无法测试,但我相信我没有犯任何错误。
您可以使用file_put_contents
将字符串写入文件。不确定您所说的输出到HTML是什么意思。
您只想要输出吗?