Mirakurun Mirakurun - 1 year ago 67
HTML Question

Read file content and store as an array

I want to read log from a file and display it as a list in my Admin panel. I was pretty much sure that this code should work, but apparently it doesn't. The loop doesn't print anything in the list, and the two lines above the loop print just the first line in the file. I guess the problem is in my construction of the array

. Since this project is my first time use of PHP (usually I work with C), don't judge.

<select name=servers size=50 style=width:1028px>

if ($start=="1") {
//start the server, this works.
elseif ($start=="2") {
$log=fopen("file.log", "r");
$asdf = sprintf ("<option >%s</option>", $log);
echo $asdf; //these two lines are for testing purposes,
//they print only one line of the file in the list.

while ($log[$i]!=null) {
$asdf[$i] = sprintf ("<option >%s</option>", $log[$i]);
echo $asdf[$i];
$i++; //this loop is the problem, doesn't print anything.
echo fread($log,filesize("file.log"));
echo $log;

Any help would be appreciated.

Answer Source

Instead of

$log=fopen("file.log", "r");



Also change the while loop to

foreach($log as $logline) {
    // print $logline the way you want

The reason why your code isn't working is that fopen returns a handle of the file and you need special functions to use it: fread, fclose, feof etc. The file() function reads the whole file into an array (each element is a line) so for small and medium-sized text files it's an ideal way to go.

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