I want to create a simple logfile in PHP that later can be read by PHP.
This logfile should look like this:
1303942306 26.4 "Lore ipsum 1" 84.169.73.55 appname1
1303942308 28.8 "Lore ipsum 2" 84.169.73.55 appname2
1304078658 31.2 "Lore ipsum 3" 80.187.103.95 appname3
As you can see it is supposed to contain the following variables:
$timestamp
$float
$text (with spaces and other special characters)
$ip
$appname
Until now there was no need to save text (with spaces) within this logfile, so I could use a simple fscanf function.
I've tried to use "|" as a delimiter with fscanf - but, well, it has a few "glitches" ;-):
//write to file
$statisticsfile = fopen("user.history",'a+b');
fputs($statisticsfile, time().' | '.$float.' | '.$text.' | '.$_SERVER['REMOTE_ADDR'].' | '.$appname."\r\n");
//read from file
while ($userinfo = fscanf($statisticsfile, "%[0-9] | %[0-9.-] | %[a-zA-Z0-9 ,] | %[0-9.] | %[0-9]"))
{list ($timestamp[], $float[], $text[], $ip[], $appname[]) = $userinfo;}
This code creates three problems:
I would really appreciate your help ;-)
From your sample data, seems to me that the best way to go is the built-in csv functions, fgetcsv and fputcsv. Simply use a space as your delimiter instead of a comma. These functions will automatically be mindful of the quoted values.