Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

file-io

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.

like image 988
enjoylife Avatar asked Mar 26 '11 07:03

enjoylife


People also ask

How do I save a string in PHP?

The file_put_contents() function in PHP is an inbuilt function which is used to write a string to a file. The file_put_contents() function checks for the file in which the user wants to write and if the file doesn't exist, it creates a new file.

Which function write the contents of a string to a file?

The write() method writes a string to a text file. The writelines() method write a list of strings to a file at once.

Can PHP write to file?

PHP Write to File - fwrite()The fwrite() function is used to write to a file. The first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to be written.


1 Answers

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.

like image 200
Frantisek Avatar answered Oct 12 '22 12:10

Frantisek