2011-10-22 38 views
2

这是我的代码:PHP读取.txt文件和编辑一行

$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)真的,除非有一个非常简单的方法来做到这一点。有人可以帮忙吗?我一直在寻找一段时间,找不到我在找什么。

+0

使用['文件()'](http://php.net/file)功能,以及一些更明智的变量名。 – mario

回答

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)); 
+0

作品,谢谢! – Oyed

+0

我从来没有记得你可以这样做,因为我被迫在PHP4中工作了很多,所以我不这样做(在<5中不起作用) - 但这可能是这种情况下最好的方法。 +1。 – DaveRandom

1

突破的最佳方式一行一行的文件是file()。这里是我会做什么(固定):

<?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); 

?>