简体   繁体   中英

How can I make the PHP write to the file automaticly?

I want to save a web page to a text file automatically or at least every second. So I wrote a PHP file like that :

<?php

$homepage = file_get_contents('www.example.com');
echo $homepage;


$myfile = fopen("file.txt", "w") or die("Unable to open file!");

while(true) {

    fwrite($myfile, $homepage);

}
    fclose($myfile);

?>

But it did not work The file will not be written until the while loop will stop. Can someone help me with that ? I need the PHP to run all the time or at least for a few minute. How can I do that ?

I'd go for something like this (not tested though)

<?php
header("Refresh:30"); // The page will be refreshed every 30 seconds
                    // To avoid max_execution_time errors

$myfile = "file.txt";

for ($i=0; $i < 30; $i++) { 
    $homepage = file_get_contents("http://www.example.com");
    echo $homepage;
    file_put_contents($myfile, $homepage);
    sleep(1); // Do it every second
}

If a second is too much time, you could use usleep instead

That's because you don't close the file in the loop. And you should add some delay too. Change it to this:

<?php
$homepage = file_get_contents('www.example.com');
echo $homepage;
while(true) {
    $myfile = fopen("file.txt", "w") or die("Unable to open file!");
    fwrite($myfile, $homepage);
    fclose($myfile);
    sleep(1);
}
?>

Note that if you're running this on a webserver, it will exceed the time limit.

First off, maybe you should consider using sleep inside your loop to minimise performance impact. After every write you should invoke flush to persist data onto disk. There is also a risk of overloading target site in a form of DOS attack, so you should be mindful of the consequences.

This is not tested but should word... But honestly your better of using Ajax with a timer to do this.

header("Refresh:60");

function writeToPage($page,$file){

    $content = file_get_contents($page);

    file_put_contents($file,$content);

}

$page = "www.example.com";

$file = "file.txt";

$write = true;

while( $write === true ) {

    sleep(5);

    writeToPage($page,$file);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM