[英]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.