vezinadj Posted December 31, 2010 Share Posted December 31, 2010 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". Quote Link to comment https://forums.phpfreaks.com/topic/223097-readwrite-text-file/ Share on other sites More sharing options...
QuickOldCar Posted December 31, 2010 Share Posted December 31, 2010 <?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"; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/223097-readwrite-text-file/#findComment-1153427 Share on other sites More sharing options...
QuickOldCar Posted December 31, 2010 Share Posted December 31, 2010 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"; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/223097-readwrite-text-file/#findComment-1153436 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.