PHP获取.txt文件并编辑一行


PHP fetching a .txt file and editing a single line

这是我的代码:

$string2 = file_get_contents('maps/' . $region . '.txt');
$string2 = explode("'n", $string2);
foreach($string2 as $value2) {
   $string2 = unserialize($value2);
   if($string2['x_pos'] == ($x2 + 4) && $string2['y_pos'] == ($y2 + 8)) {
      $length2 = strlen($string2['amount']);
      $new_amount = ($string2['amount'] + 0) - ($resource_quantity + 0);
      $changed = substr_replace($value2, $new_amount, 123, $length2);
      file_put_contents('maps/' . $region . '.txt', $changed);
      break 1;
   }
}

我想让代码做的是打开文件,读取每一行,直到找到它想要的行,然后用编辑的行重新保存文件。问题是,它可以工作,但它只将其与编辑行保存在一起,并删除所有其他行。

我想保持我使用的方法(file_get_contents &File_put_contents),除非有一种非常简单的方法。有人能帮帮我吗?

我已经找了一段时间了,找不到我要找的东西。

您需要将写操作移到循环之后,并让它写入从文件中读取的所有内容。当前的方式是,它将所有内容替换为$changed(只有一行)。

以上,除了稍微改进了代码之外,还导致了:

$filename = 'maps/' . $region . '.txt';
$lines = file($filename);
foreach($lines as &$line) { // attention: $line is a reference
    $obj = unserialize($line);
    if(/* $obj satisfies your criteria*/) {
        $line = /* modify as you need */;
        break;
    }
}
file_put_contents($filename, implode("'n", $lines));

试着这样做:http://php.net/file(将整个文件读取到数组中)

按行拆分文件的最佳方法是使用file()。下面是我要做的(FIXED):

<?php
  // This exactly the same effect as your first two lines
  $fileData = file("maps/$region.txt");
  foreach ($fileData as $id => $line) {
    // This is probably where your problem was - you were overwriting
    // $string2 with your value, and since you break when you find the
    // line, it will always be the line you were looking for...
    $line = unserialize($line);
    if ($line['x_pos'] == ($x2 + 4) && $line['y_pos'] == ($y2 + 8)) {
      $amountLen = strlen($line['amount']);
      // Sorry, adding zero? What does this achieve?
      $new_amount = $line['amount'] - $resource_quantity;
      // Modify the actual line in the original array - by catching it in
      // $changed and writing that variable to file, you are only writing
      // that one line to file.
      // I suspect substr_replace is the wrong approach to this operation
      // since you seem to be running it on PHP serialized data, and a
      // more sensible thing to do would be to modify the values in $line
      // and do:
      // $fileData[$id] = serialize($line);
      // ...however, since I can;t work out what you are actually trying
      // to achieve, I have fixed this line and left it in.
      $fileData[$id] = substr_replace($fileData[$id], $new_amount, 123, $amountLen);
      break;
    }
  }
  file_put_contents("maps/$region.txt", $fileData);
?>