简体   繁体   English

PHP | fopen()&fwrite()在我的脚本中不起作用?

[英]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. 当我把fopen()放在循环之外时,我没有看到任何数据进入文件。 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. 当我在循环的最后2个条件中使用fopen()打开文件时,我确实得到了更新,我可以实时看到它们。

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如何工作的fopen()。

<?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 :) 希望它能帮到你:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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