2011-07-28 42 views
1

我有一個包含100分高分的遊戲我的腳本文件就行了。讀取一個文件,並返回一個包含

1.2345, name1 
1.3456, name2 
1.4567, name3 

例如。

,使用PHP,我需要得到nameX出現在這樣我就可以將其覆蓋,如果新的得分比老得分越高,行的內容。此外,我需要找出其中的行號,讓他們知道什麼地方(居)nameX出現在他們英寸

我應該看哪個PHP函數成這樣我可以使這項工作?

+3

做你自己一個大忙,並開始使用數據的基礎上 – 2011-07-28 04:37:00

回答

4

您可以使用fopenfreadfile這一個。就個人而言,我會選擇文件,因爲它聽起來像這是一個相當小的文件開始。

$row = -1; 
$fl = file('/path/to/file'); 

if($fl) 
{ 
    foreach($fl as $i => $line) 
    { 
     // break the line in two. This can also be done through subst, but when 
     // the contents of the string are this simple, explode works just fine. 
     $pieces = explode(", ", $line); 
     if($pieces[ 1 ] == $name) 
     { 
      $row = $i; 
      break; 
     } 
    } 
    // $row is now the index of the row that the user is on. 
    // or it is -1. 
} 
else 
{ 
    // do something to handle inability to read file. 
} 

良好的措施,則fopen方法:

// create the file resource (or return false) 
$fl = fopen('/path/to/file', 'r'); 
if(!$fl) echo 'error'; /* handle error */ 

$row = -1; 
// reads the file line by line. 
while($line = fread($fl)) 
{ 
    // recognize this? 
    $pieces = explode(", ", $line); 
    if($pieces[ 1 ] == $name) 
    { 
     // ftell returns the current line number. 
     $row = ftell($fl); 
     break; 
    } 
} 
// yada yada yada 
+0

它不應該是如果($件[1] == $名)? – bfavaretto

+0

@bfavaretto是的。固定。 – cwallenpoole

2

這裏是我一直推薦的鏈接,而且也從未到目前爲止還沒有。

Files in php

從鏈接:

<?php 

// set file to read 
$file = '/usr/local/stuff/that/should/be/elsewhere/recipes/omelette.txt' or die('Could not read file!'); 
// read file into array 
$data = file($file) or die('Could not read file!'); 
// loop through array and print each line 
foreach ($data as $line) { 
    echo $line; 
} 

?> 
0

首先,你需要閱讀所有的文件內容了。修改你想要的行,然後把它們一起放回文件。但是,如果您同時運行腳本,這將具有性能和穩定性。

相關問題