【问题标题】:Edit specific record from a line in text file and PHP从文本文件和 PHP 中的一行编辑特定记录
【发布时间】:2013-09-25 07:48:35
【问题描述】:

我正在尝试使用 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
  }
}

问题是我不能改变新闻点击率!例如,我需要将第二行的命中从 241 更改为 242 并将其再次写入 txt 文件。

我在这个网站和谷歌上搜索并尝试了一些方法,但我无法解决这个问题。

【问题讨论】:

    标签: php file text


    【解决方案1】:

    至少,您忘记将增量写回文件。此外,您还需要将每一行解析为可以使用的列(由管道 | 分隔)。

    未经测试的代码,但想法是:

    $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
    

    【讨论】:

      【解决方案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);
      

      就是这样! :)

      【讨论】:

      • 但它没有编辑第二行,之后我得到了太多的空行!
      • 我给了你一个处理数据的解决方案,不仅仅是增加一个字段,但你没有通过树木看到森林。
      • 不客气。要编辑第二行,只需将$News[2]['views']++; 放在两段代码之间(第一行是用文件中的所有数据创建一个数组,第二行将该数组写入磁盘)。
      猜你喜欢
      • 1970-01-01
      • 2010-12-30
      • 1970-01-01
      • 2011-06-10
      • 2013-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多