簡體   English   中英

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

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

大家。 我有一個循環運行的腳本,其結構類似於下面的那個。

當我把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.
        }
    }

}

希望它能幫到你:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM