简体   繁体   English

PHP,将数组保存到文件中

[英]PHP , save array to a file

I have a simple hit counter where I save the IP and country of visitors, but after some hits the file where I write the visits fills with empty lines 我有一个简单的点击计数器,我保存访问者的IP和国家,但在一些点击我写的访问文件填充空行

This is the result: 这是结果:

<myip>|GR







<myip>|GR



<myip>|GR

<myip>|GR
<myip>|GR

This is the code: 这是代码:

<?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);
    }
?>

So why do I end up with a file with empty lines? 那么为什么我最终得到一个空行的文件?

You just have to change this: 你只需要改变这个:

$newEntries=implode($entries,"\n");

$fp = fopen("hitcounter.txt" ,"w");
fputs($fp , $newEntries);
fclose($fp);

to this: 对此:

file_put_contents("hitcounter.txt", $entries);

Because if you read the file into the array with file() you already have the new line characters at the end of each element, so if you implode it you going to add a new line character to each element. 因为如果使用file()将文件读入数组,则每个元素的末尾都有新的行字符,因此如果你将其删除,则会为每个元素添加一个新的行字符。

That you have the new line character also in your new entire you just have to append it in your array_push like this: 你有新的整行字符,你只需要将它添加到你的array_push中,如下所示:

array_push($entries, $ip."|". "GR" . PHP_EOL);
                                   //^^^^^^^

Also if you don't use the data from the file anywhere else in your code you could also just append the new entry, so your could could look something like this: 此外,如果您不在代码中的任何其他位置使用文件中的数据,您也可以添加新条目,因此您可能看起来像这样:

$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.

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