簡體   English   中英

PHP,將數組保存到文件中

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM