Rilcon42
Rilcon42

Reputation: 9765

readfile() is not returning the file contents

I am trying to split the string below on all <br> but for some reason my loop returns one giant string.

if (file_exists("/home/pi/Desktop/PiControl/status_log"))
    {
        $file = readfile("/home/pi/Desktop/PiControl/status_log");
        $arr = explode("<br>", $file);
        // $file = array_slice($file, count($file) - 5);
        // $file = array_reverse($file);
        foreach ($arr as $f)
        {
            echo $f;
            echo "WOO";
        }   
        fclose($file);
    }
    else
    {
        echo "no file found";
    }

contents of the file:

<br>light is now: on 2015-06-01 03:32:42.902387<br>light is now: off 2015-06-01 03:32:54.360173<br>light is now: on 2015-06-01 03:33:07.781693<br>light is now: off 2015-06-01 03:33:15.867386<br>light is now: on 2015-06-01 03:34:42.683736<br>light is now: off 2015-06-01 03:34:45.205557<br>light is now: on 2015-06-01 03:36:18.037309<br>light is now: off 2015-06-01 03:36:25.915424<br>light is now: on 2015-06-01 03:36:58.261714<br>light is now: off 2015-06-01 03:37:05.103494<br>light is now: on 2015-06-01 11:00:01.735592<br>light is now: off 2015-06-01 13:06:50.254778<br>light is now: on 2015-06-01 17:28:11.218417

should return:

light is now: on 2015-06-01 03:32:42.902387
WOO
light is now: off 2015-06-01 03:32:54.360173
WOO
.....

Upvotes: 0

Views: 27

Answers (1)

Rizier123
Rizier123

Reputation: 59681

readfile() doesn't return the file as you can read in the manual:

Returns the number of bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as @readfile(), an error message is printed.

I think what you want to do is this:

if(file_exists("/home/pi/Desktop/PiControl/status_log")) {

    $lines = explode("<br>", file_get_contents("/home/pi/Desktop/PiControl/status_log"));

    foreach($lines as $line) {
        echo $line . "<br>";
        echo "WOO<br>";
    }


} else {
    echo "no file found";
}

Upvotes: 1

Related Questions