繁体   English   中英

PHP从文件foreach加载数组

[英]PHP load array from file foreach

我有以下代码:

require("class.XMLHttpRequest.php");
function hot($news){
 $url="https://localhost/search.aspx?search=".$news.""; 
 $ajax=new XMLHttpRequest();
 $ajax->setRequestHeader("Cookie","Cookie: host");
 $ajax->open("GET",$url,true);
 $ajax->send(null);
 if($ajax->status==200){
  $rHeader=$ajax->getResponseHeader("Set-Cookie");
  if(substr_count($rHeader, "Present!")>0) { return true; }
 }else{ return false; }
} 

$celebrities = array('britney','gaga','carol');
$filename = 'result.txt';
$handle = fopen($filename, 'a');
foreach($celebrities as $celebrity)
{
    if(hot($celebrity)) { fwrite($handle, "{$celebrity}\r\n"); };
}
fclose($handle);

而不是

$celebrities = array('britney','gaga','carol');
$filename = 'result.txt';
$handle = fopen($filename, 'a');
foreach($celebrities as $celebrity)
{
    if(hot($celebrity)) { fwrite($handle, "{$celebrity}\r\n"); };
}
fclose($handle);

我要实施

$read_file = fopen('array.txt', 'r');
$write_file = fopen('result.txt', 'a');

while(!feof($read_file))
{
    $celebrity = fgets($read_file);
    if(hot($celebrity)) { fwrite($handle, "{$celebrity}\r\n"); }
}

fclose($write_file);
fclose($read_file);

现在result.txt不再写了,我哪里出错了? 脚本应该从文件中读取数组,热处理函数,然后将每个结果记录在result.txt的新行中,谢谢!

假设每行有一个名人:

$celebrity = trim(fgets($read_file));

由于fgets将返回包含换行符的字符串。

在线上:

if(hot($celebrity)) { fwrite($handle, "{$celebrity}\r\n"); }

您使用$handle ,不再定义。 您想改用$write_file

if(hot($celebrity)) { fwrite($write_file, "{$celebrity}\r\n"); }

暂无
暂无

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

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