Jump to content

Read/Write text file


vezinadj

Recommended Posts

I very new to php and all I am simply trying to do is read the contents of a text file and echo it out on the screen.

I have tried many things to see what I am doing wrong but it just simply isnt working for me. I know the server I am using has php enabled as well because I have tried a simple echo and it works fine.

 

This is the code I am currently using.

 

<?php

$file = fopen(file.txt", 'r');

$read = fread($file, '6')

echo $read;

?>

 

also, I have tried this.

 

<?php

$file = file_get_contents('file.txt');

echo $file;

?>

 

I have a file.txt on the server I am using in the same directory as index.php, I feel like this should be working but I get no result!

Alls I have in the text file is a statement that says "hello world".

Link to comment
https://forums.phpfreaks.com/topic/223097-readwrite-text-file/
Share on other sites

<?php
$my_file = "file.txt";
if (file_exists($my_file)) {
$data = file($my_file);
$total = count($data);
echo "<br />Total lines: $total<br />";
foreach ($data as $line) {
echo "$line<br />";
}
} else {
echo "No file to display";
}
?>

Link to comment
https://forums.phpfreaks.com/topic/223097-readwrite-text-file/#findComment-1153427
Share on other sites

Really should read up some tutorials on read and write to text files, but as for a simple example to add a new line can do this.

 

If you keep visiting the new php file you made you will see it adding the new lines every refresh.

 

<?php
//read a file
$my_file = "file.txt";
if (file_exists($my_file)) {
$data = file($my_file);
$total = count($data);
echo "<br />Total lines: $total<br />";
foreach ($data as $line) {
echo "$line<br />";
}

//the a+ is add
$write = fopen($my_file, 'a+');
$message = "I just added this line\r\n";
fputs($write, $message);
fclose($write);

/*note the w, this will overwrite the entire contents
$write = fopen($my_file, 'w');
$message = "I just added this line\r\n";
fputs($write, $message);
fclose($write);
*/

} else {
echo "No file to display";
}
?>

Link to comment
https://forums.phpfreaks.com/topic/223097-readwrite-text-file/#findComment-1153436
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.