菲律宾比索 |fopen() 和 fwrite() 在我的脚本中不起作用


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

everyone.我有一个循环运行的脚本,其结构类似于下面的结构。

当我把 fopen() 放在循环之外时,我没有看到任何数据进入文件。当我在循环的最后 2 个条件中使用 fopen() 打开文件时,我确实会得到更新,并且可以实时看到它们。

问题是这个脚本可以运行很长时间。而且由于我没有看到正在更新的输出文件,因此我不知道它是否有效。

如果没有,那为什么它不起作用?如何修复?我假设有一些我只是不知道关于 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");
        }
    }
}
?>  

提前感谢,女孩。

你错过了放一个"

取代

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

由:

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

你的代码应该是:-

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.
        }
    }
}

希望它能帮助你:)