我正在创建一个点击计数器。 注册访问者在那里的脚本会创建一个像这样的.txt文件
IP Adress:127.0.0.1
Timestamp:1400602795
User Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36
Times visited:1
我希望能够获得时间戳和访问时间等信息。 我想这样做的一种方法是创建一个由“:”分隔的数组。
我试图创建数组,但由于某种原因“Times Visited”没有包含在数组中。以下是该尝试的代码:
$fileResource = @fopen("hits/".$_SERVER["REMOTE_ADDR"].".txt","r");
$fileContent = @fread($fileResource,100000);
$array = preg_match_all("/(.*):(.*)\\n/i",$fileContent,$fileMatches);
//0 = IP
//1 = Timestamp
//2 = User Agent
//3 = Times Visited
echo $fileMatches[0][3];
这是我尝试print_r($ fileMatches)
时的输出Array
( [0] =>排列 ( [0] => IP地址:127.0.0.1
[1] => Timestamp:1400604101
[2] => User Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36
)
[1] => Array
(
[0] => IP Adress
[1] => Timestamp
[2] => User Agent
)
[2] => Array
(
[0] => 127.0.0.1
[1] => 1400604101
[2] => Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36
)
)
答案 0 :(得分:1)
如果您已将文件的全部内容读入字符串,则可以使用explode
两次,如下所示:
$s = <<<EOT
IP Address:127.0.0.1
Timestamp:1400602795
User Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36
Times visited:1
EOT;
$arr = array();
foreach (explode("\n", $s) as $line) {
if (trim($line) !== '') { // check for empty line
list($key, $value) = explode(':', $line);
$arr[$key] = trim($value);
}
}
print_r($arr);
这会创建一个这样的数组:
Array (
[IP Address] => 127.0.0.1
[Timestamp] => 1400602795
[User Agent] => Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36
[Times visited] => 1
)
或者,您可以使用fread
逐个阅读每一行,而不是使用fgets
,而是将foreach
循环替换为while (fgets($fileResource))