For循环循环到文本文件中的最后一项


for loop looping to tlast item in text file

我一直在努力让这个工作任何帮助将非常感谢。我尝试了许多方法来获得这项工作,但我要么得到这个错误,域名参数是空的,要么我得到txt文件中的最后一个域。TXT文件每行只有一个域。

 $address="file.txt";
  $shit=fopen($address,"r");
 $contents2= fread($shit,filesize($address));

//also tried $domainlist=explode("'n'r",$contents2);
    $domainlist=explode("'n",$contents2);
   for($i=0 ; $i<=count($domainlist); ++$i){
    $domainlist[$i]=$domain;
$contents = file_get_contents("http://www.whoisxmlapi.com/whoisserver/WhoisService?
domainName=$domain&username=$username&password=$password&outputFormat=JSON");

$results=json_decode($contents);

print_r($results);
  unset($domain);
  };
?>

更容易:

$lines = file("file.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach($lines as $domain) {
    $contents = file_get_contents("http://www.whoisxmlapi.com/whoisserver  /WhoisService?domainName=$domain&username=$username&password=$password&outputFormat=JSON");
    $results  = json_decode($contents);
    print_r($results);
}

您可能想要trim($domain)或确保它有效或在执行file_get_contents()之前进行其他检查。

$file = fopen("file.txt", "r");
while(!feof($file)){
    $line = fgets($file);
    $last_line = $line;
}
fclose($file);
echo $last_line;

有几种方法可以做到这一点…

$file = file("file.txt");
foreach($file as $line) {
  // do something with the $line
}

我更喜欢这种方法,除非你不确定文件大小。如果不确定,可以考虑使用fopen