如何将一个字符串放入PHP中的文本文件? [英] How to put the a string into a text file in PHP?

查看:101
本文介绍了如何将一个字符串放入PHP中的文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在php中将一个字符串放入一个txt文件?



我想写这样的字符串:

  1,hello ,世界! 
2,欢迎

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

解决方案

要写入一个txt文件:

 <?php 
$ file ='file.txt';
$ data ='这是你写的字符串';
file_put_contents($ file,$ data);
?>

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

 <?php 
//将这段代码放在任何你想要的文件内容出现
readfile('file.txt');
?>

编辑:

问题来自评论:

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

 < ?php 
$ contents = file_get_contents('file.txt');
$ contents = explode(\\\
,$ contents);
foreach($ contents as $ line){
$ firstComma =(strpos($ line,,))+ 1;
$ newLine = substr($ line,$ firstComma);
echo $ newLine。\\\
;
}
?>

试试吧。我没有我的服务器在这里,所以我不能测试它,但我相信我没有犯任何错误。


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

I want to write string like this:

        1,hello,world!
        2,welcome

Then have those two lines be in the file.

解决方案

To write to a txt file:

<?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
// 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.

这篇关于如何将一个字符串放入PHP中的文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆