PHP从文件foreach加载数组

时间:2010-09-30 15:45:20

标签: php arrays 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不再写了,我哪里出错了? 脚本应从文件中读取数组,处理函数hot,然后在result.txt中的新行中写入每个reasults 提前谢谢!

2 个答案:

答案 0 :(得分:1)

假设每行有一个名人:

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

由于fgets将返回字符串,包括换行符。

答案 1 :(得分:0)

在线:

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

您使用不再定义的$handle。您希望改为使用$write_file

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