Reputation: 23178
I have a file that contains 100 highscores for a game I'm scripting.
1.2345, name1
1.3456, name2
1.4567, name3
for example.
With php, I need to get the content of the line nameX appears on so I can overwrite it if the new score is higher than the old score. Also I need to find out which line number nameX appears on so they know what place (ranking) they are in.
Which php functions should I look into so that I can make this work?
Upvotes: 1
Views: 115
Reputation: 82028
You can either use fopen
and fread
or file
for this one. Personally, I would opt for file as it sounds like this is a fairly small file to begin with.
$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.
}
For good measure, the fopen approach:
// 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
Upvotes: 4
Reputation: 932
First you need to read all the file content out. Modifiy the line you desire, then put them all together back the file. This however will have performance and constitancy prolbems if you running scripts simultaneous.
Upvotes: 0
Reputation: 43810
Here is a link that i always recommend, and it never failed so far.
From Link:
<?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;
}
?>
Upvotes: 2