简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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