简体   繁体   中英

PHP | fopen() & fwrite() Not Working in My Script?

everyone. I have a script that runs with a loop, whose structure is like the one below here.

When I put the fopen() outside of the loop, I don't see any data coming to the file. When I open the file with fopen() inside the 2 last conditions of the loop, I do get updates, and I can see them in real time.

The thing is that this script could run for very long. And Since I don't see the output file being updated, I don't know if it does even work.

If it doesn't, then why does it not work? And how can it be fixed? I assume there's something that I just don't know about execution and fopen() regarding how PHP works.

<?php   

ini_set('max_execution_time', 0);

$output_file = fopen("output.txt, "a");

for ($i = 0; 50000 < $max_run; $i) { 

    $url = "http://www.some-website.com/whatever?parameter=value

    $html_file = file_get_contents($url);

    $doc = new DOMDocument();
    @$doc->loadHTML($html_file);

    $xpath = new DOMXpath($doc);

    $extracted_data = $xpath->query('//whatever')[-999]->textContent;

    if (whatever){

        if (-some-condition) { 
            fwrite($output_file, $extracted_data."\n");
        }

        if (-something-else) {
            fwrite($output_file, "other-data"."\n");
        }
    }

}

?>  

Thanks in advance, Gal.

You miss to put a "

Replace

$output_file = fopen("output.txt, "a");

By :

$output_file = fopen("output.txt", "a");

Your code should be:-

ini_set('max_execution_time', 0);
// You have missed " in below line.
$output_file = fopen("output.txt", "a");

for ($i = 0; 50000 < $max_run; $i) { 
    // You have missed " and ; in below line.
    $url = "http://www.some-website.com/whatever?parameter=value";

    $html_file = file_get_contents($url);

    $doc = new DOMDocument();
    @$doc->loadHTML($html_file);

    $xpath = new DOMXpath($doc);

    $extracted_data = $xpath->query('//whatever')[-999]->textContent;
    // Added this line here.
    $extracted_data .= "\n";
    if (whatever){

        if (-some-condition) { 
            //fwrite($output_file, $extracted_data."\n");
            file_put_contents($output_file, $extracted_data);
            // I have used file_put_contents here. fwrite is also fine.
        }

        if (-something-else) {
            //fwrite($output_file, "other-data"."\n");
            file_put_contents($output_file, "other-data"."\n");
            // I have used file_put_contents here. fwrite is also fine.
        }
    }

}

Hope it will help you :)

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