-5

Currently, I have this code to return the last 10 lines in the file: food.txt

<?php
echo `tail /home/food.txt`;

and the output returns something like:

pie apple orange fish lemon peach egg bacon pancake strawberry

The problem is, running the tail command in PHP is ignoring the lines originally in the file food.txt, if I run the same command over SSH, I get:

pie 
apple 
orange 
fish 
lemon 
peach 
egg 
bacon 
pancake 
strawberry

I cannot use PHP to open the file (from my knowledge) because the file will grow pretty large over time and I'm not sure PHP will be able to handle it, and by large, I mean 250,000+ lines.

Thanks.

  • 3
    Does "output returns something like" perhaps only apply to viewing it within a web page? (Linebreaks do not break flow text in HTML per default.) – mario Aug 30 '14 at 01:43
  • Why cannot PHP handle such a large file (that I believe does not exist anyway). Besides apie with apples, lemon and bacon in it does sound tasty – Ed Heal Aug 30 '14 at 01:44
  • Do you have to store all the content in one single file? You should seriously consider dynamically creating multiple files, each with a character limit. This way, you only have to retrieve the last file created. – Ryan Smith Aug 30 '14 at 01:44
  • @EdHeal It is possible PHP will reach its memory limit when buffering this large of a string. Or, at least, the page will take a while to load. – Ryan Smith Aug 30 '14 at 01:46
  • Whys wrong with using tail -n10 /path/to/file.txt it appears you are using a unix system. so you would use ob_start(); then system("tail -n10 /path/to/file.txt"); $output = ob_get_contents(); ob_end_clean(); echo $output; You may wish to explode this.. this code wont work on a host that doesnt have the tail command in its shell. – Daryl B Aug 30 '14 at 01:49
  • @RyanSmith - Just read the file line by file. Not the whole thing. – Ed Heal Aug 30 '14 at 01:50
  • 2
    Looks like what you really need is a database. – jeroen Aug 30 '14 at 01:55

2 Answers2

1

If the problem is missing line breaks (not clear from the question) wrap everything in <pre>.

echo '<pre>';
echo `tail /home/food.txt`;
echo '</pre>';

Edited to add: <pre> will give you a monospace font by default; you can fix that easily with CSS if it's a problem.

Bob Brown
  • 1,463
  • 1
  • 12
  • 25
0

We can use only one <pre> tag

First

echo '<pre>';
echo 'tail /home/food.txt';

Second

$string = 'tail /home/food.txt';
echo str_replace(" " ,"\n", $string);
AbcAeffchen
  • 14,400
  • 15
  • 47
  • 66
Devesh
  • 1
  • 1