Search code examples
phpfopenfwrite

Trying to create a text file with information.


I am trying to make some statistics in a text document.

I need to have a new unique text document for each item, so therefor I have not made any text documents for now.

But I got this function which I call with the unique ID for the item.

function statestics($id) {
    $filename = 'cache/statestics/opskrift-'.$id.'.txt';

    if(!file_exists($filename)) {
       $fp = fopen($filename,"w");
       fwrite($fp,"0");
       fclose($fp);
    }

    $date = date('d-m-Y');
    $date_exist = 0;
    $todays_num = 0;
    $check1 = explode(',',file_get_contents($filename));
    $content = file_get_contents($filename);
    foreach ($check1 AS $c) {
        $check2 = explode(':',$c);
        if ($check2[0] == $date) {
            $date_exist = 1;
            $todays_num = $check[1];
        }
    }
    if ($date_exist) {
        $insert = $date . ':' . $todays_num . ',';
        $content = str_replace($insert, "", $content);
    }
    $todays_num + 1;
    $content = $content . $insert;
    file_put_contents($filename, $content);
}

But when I run this, it doesn't actually create a single text documents. Any ideas? No errors are reported.


Solution

  • To concat string value on end of file should do this:

    $fp = fopen($filename,"a+");
    

    If the file exist he just go to end of the file, else he create it.

    To use file_get_content and file_put_content, take a look in: here and here

    GL