大家。我有一个循环运行的脚本,其结构类似于下面的那个。
当我把fopen()放在循环之外时,我没有看到任何数据进入文件。当我在循环的最后2个条件中使用fopen()打开文件时,我确实得到了更新,我可以实时看到它们。
事情是这个脚本可以运行很长时间。由于我没有看到输出文件正在更新,我不知道它是否确实有效。
如果它没有,那为什么它不起作用?它怎么能修复? 我假设有一些我不了解执行和fopen()关于PHP如何工作的东西。
<?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");
}
}
}
?>
提前致谢, 加仑
答案 0 :(得分:1)
您错过了"
替换
$output_file = fopen("output.txt, "a");
通过:
$output_file = fopen("output.txt", "a");
答案 1 :(得分:1)
您的代码应该是: -
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.
}
}
}
希望它会对你有所帮助:)。