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

How to put line in txt file in php?

I want to write a line like this:

1,hello,world! 2,welcome 

Then these two lines are in the file.

+6
php file-io
source share
2 answers

To write to the txt file:

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

To display the contents of this file somewhere on the page (remember that 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 another question from the comments:

When saving your data to a file, the source code is fine, just use this. Another code appears when the contents of the file are echoed, so it will now 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 this. I do not have my server here, so I can not test it, but I believe that I was not mistaken there.

+12
source share

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

+1
source share

All Articles