我有一个简单的点击计数器,在这里我保存了访问者的IP和国家,但是在一些点击了我写的文件之后,访问就充满了空行。
--这是结果:
<myip>|GR
<myip>|GR
<myip>|GR
<myip>|GR
<myip>|GR这是代码:
<?php
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
$location = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));
$entries = file("hitcounter.txt");
array_push($entries,$ip."|".$location->country);
$newEntries=implode($entries,"\n");
$fp = fopen("hitcounter.txt" ,"w");
fputs($fp , $newEntries);
fclose($fp);
function echoVisits(){
$entries = file("hitcounter.txt");
echo count($entries);
}
?>那么,为什么我最终会得到一个空行的文件呢?
发布于 2015-04-08 09:51:56
你只需要改变这个:
$newEntries=implode($entries,"\n");
$fp = fopen("hitcounter.txt" ,"w");
fputs($fp , $newEntries);
fclose($fp);对此:
file_put_contents("hitcounter.txt", $entries);因为如果使用file()将文件读入数组中,那么在每个元素的末尾已经有了新的行字符,所以如果将其内爆,将向每个元素添加一个新的行字符。
如果在新的整个系统中都有新的行字符,那么只需在array_push中添加它,如下所示:
array_push($entries, $ip."|". "GR" . PHP_EOL);
//^^^^^^^另外,如果您不使用代码中其他任何地方的文件中的数据,您也可以附加新条目,这样您就可以这样做:
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
$location = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));
file_put_contents("hitcounter.txt", $ip."|". $location->country . PHP_EOL, FILE_APPEND);
function echoVisits($file){
return count(file($file));
}https://stackoverflow.com/questions/29511277
复制相似问题