[英]PHP , save array to a file
我有一个简单的点击计数器,我保存访问者的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);
}
?>
那么为什么我最终得到一个空行的文件?
你只需要改变这个:
$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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.