PHP,将数组保存到文件中

PHP,将数组保存到文件中,php,arrays,file,Php,Arrays,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(

我有一个简单的点击计数器,在那里我保存了访问者的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);
    }
?>
| GR
|GR
|GR
|GR
|GR
这是代码:

<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($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));
}

此外,如果您不在代码中的任何其他位置使用文件中的数据,您也可以只附加新条目,这样您的代码看起来可能类似于:

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

你的问题是?我想他想从代码中省略多余的行@Rizier123@Rizier123,我觉得很明显。。。正如测试人员所说,我不想要空行。。。