enjoylife enjoylife - 1 year ago 64
PHP Question

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

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

I want to write string like this:


Then have those two lines be in the file.

Answer Source

To write to a txt file:

$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):

// place this piece of code wherever you want the file contents to appear


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:

$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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download