1

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

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
  }
}

問題は、ニュースのヒットを変更できないことです。たとえば、2 行目のヒット数を241から242に変更し、txt ファイルに再度書き込む必要があります。

このサイトとGoogleで検索して、いくつかの方法を試しましたが、修正できませんでした。

4

2 に答える 2

5

少なくとも、インクリメントをファイルに書き戻すのを忘れています。また、各行を処理可能な列に解析する必要があります (パイプで区切られます|)。

テストされていないコードですが、アイデアは次のとおりです。

$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
于 2013-09-25T07:56:51.477 に答える
2

ファイルを読み取って、次のようにすることができます。

//Get Source
$Source = ENGINE_DIR . '/data/top.txt';
$Read = file($Source);

$News = array();

foreach ($Read as $line) {
    list($id, $views, $date) = explode('|', $line);
    $News[$id] = array(
        'id' => $id,
        'views' => $views,
        'date' => $date,
    );
}

この時点$Newsで、すべてのニュース項目を含む配列があり、必要に応じて変更できます (例: $News[2]['views'] = 242;)。

今欠けているのは、ファイル部分への書き戻しだけです。これも簡単です。

$fh = fopen(ENGINE_DIR . '/data/top.txt', 'w'); //'w' mode opens the file for write and truncates it

foreach ($News as $item) {
    fwrite($fh, $item['id'] . '|' . $item['views'] . '|' . $item['date'] . "\n");
}

fclose($fh);

以上です!:)

于 2013-09-25T07:56:03.737 に答える