我正试图用PHP和文本文件制作一个简单的新闻点击计数器.我写了一个简单的代码来检查和读取文件:
文本文件:
//Data in Source File
//Info: News-ID|Hits|Date
1|32|2013-9-25
2|241|2013-9-26
3|57|2013-9-27
Run Code Online (Sandbox Code Playgroud)
PHP文件:
//Get Source
$Source = ENGINE_DIR . '/data/top.txt';
$Read = file($Source);
//Add New Record
foreach($Read as $News){
//Match News ID
if($News[0] == "2"){
//Add New Record and Update the Text File
}
}
Run Code Online (Sandbox Code Playgroud)
问题是我无法改变新闻点击!例如,我需要将第二行的匹配从241更改为242并再次将其写入txt文件.
我在这个网站和谷歌搜索并尝试了一些方法,但我无法解决这个问题.
至少,您忘记将增量写回文件.此外,您将要将每行解析为可以使用的列(由管道分隔|
).
未经测试的代码,但想法是:
$Source = ENGINE_DIR . '/data/top.txt'; // you already have this line
$Read = file($Source); // and this one
foreach ( $Read as $LineNum => $News ) { // iterate through each line
$NewsParts = explode('|',$News); // expand the line into pieces to work with
if ( $NewsParts[0] == 2 ) { // if the first column is 2
$NewsParts[1]++; // increment the second column
$Read[$LineNum] = implode('|',$NewsParts); // glue the line back together, we're updating the Read array directly, rather than the copied variable $News
break; // we're done so exit the loop, saving cycles
}
}
$UpdatedContents = implode(PHP_EOL,$Read); // put the read lines back together (remember $Read as been updated) using "\n" or "\r\n" whichever is best for the OS you're running on
file_put_contents($Source,$UpdatedContents); // overwrite the file
Run Code Online (Sandbox Code Playgroud)