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

时间:2011-10-22 13:21:17

标签: php

这是我的代码:

$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),除非有一种非常简单的方法。有人可以帮忙吗?我一直在寻找一些时间,找不到我想要的东西。

3 个答案:

答案 0 :(得分:4)

你需要在循环之后移动写操作,并让它写下你从文件中读取的所有内容。你现在拥有它的方式,只用$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));

答案 1 :(得分:1)

尝试使用:http://php.net/file(将整个文件读入数组)

答案 2 :(得分:1)

逐行打破文件的最佳方法是使用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);

?>