php 如何将字符串放入PHP中的文本文件中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5440912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:25:41  来源:igfitidea点击:

How to put the a string into a text file in PHP?

phpfile-io

提问by enjoylife

How do I put a string into a txt file in php?

如何将字符串放入php中的txt文件?

I want to write string like this:

我想写这样的字符串:

        1,hello,world!
        2,welcome

Then have those two lines be in the file.

然后将这两行放在文件中。

回答by Richard Rodriguez

To write to a txt file:

要写入 txt 文件:

<?php
$file = 'file.txt';
$data = 'this is your string to write';
file_put_contents($file, $data);
?>

To echo contents of that file somewhere on a page (remember the page must have a .php extension for php to work):

要在页面某处回显该文件的内容(请记住,该页面必须具有 .php 扩展名才能使 php 工作):

<?php
// place this piece of code wherever you want the file contents to appear
readfile('file.txt');
?>

EDIT:

编辑:

To answer your another question from the comments:

从评论中回答您的另一个问题:

When saving your data to the file, the original code is OK, just use that. The different code comes when echoing the contents from the file, so now it will look like this:

将数据保存到文件时,原始代码是可以的,只需使用它。当从文件中回显内容时会出现不同的代码,所以现在它看起来像这样:

<?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"; 
}
?>

Try it like that. I don't have my server here, so I cannot test it, but I believe I didn't make any mistake there.

就这样试试。我这里没有我的服务器,所以我无法测试它,但我相信我在那里没有犯任何错误。

回答by Rob Agar

You can write a string to a file with file_put_contents. Not sure what you mean by output to HTML.
Do you just want echo?

您可以将字符串写入带有file_put_contents. 不确定输出到 HTML 是什么意思。
你只是想要回声吗?