Forum Moderators: coopster

Message Too Old, No Replies

How can I read and pull bits from a .txt file?

         

Choach

1:34 am on Jun 18, 2004 (gmt 0)

10+ Year Member



I would like to pull text from a text file, but at irregular positions(sort of). I would like to do this for a simple high score list from some flash games.

Here is an example of the text file:

&name1=joey&score1=23453&name2=suzie&score2=21985&name3=billie&score3=2426&name4=bubba&score4=930

I simply want the first place name and score which is indicated by &name1= and &score1= to be read from the file and displayed to a webpage. Im going to repeat this function to about 6 other text files, but I think I can handle that part. Im having trouble with parsing the text of course.

Any help would be greatly appreciated.

WhosAWhata

3:54 am on Jun 18, 2004 (gmt 0)

10+ Year Member



<?
$file = "scores.txt";
$data = file_get_contents($file);
$sets = explode("&",$data);
foreach($sets as $k => $v){
if($v) {
$d = explode("=",$v);
${$d[0]} = $d[1];
}
}
?>

this will read in your variables
example:
adding this file
&name1=joey&score1=23453&name2=suzie&score2=21985

would be the same as adding this code

$name1 = "joey";
$score1 = "23453";
$name2 = "suzie";
$score2 = "21985";

then you can just display them with an echo statement

Choach

3:31 pm on Jun 18, 2004 (gmt 0)

10+ Year Member



Thanks so much for the code. I dont think I would have ever come up with that. ;) You made it look so simple.

I did have to do one thing to get it to work. After doing some research on my error message, I realized I had to add this to the page to get file_get_contents to work, due to me running PHP 4.2.3 on my server:


<?php
if (!function_exists('file_get_contents'))
{
function file_get_contents($filename, $use_include_path = 0)
{
$file = @fopen($filename, 'rb', $use_include_path);
if ($file)
{
if ($fsize = @filesize($filename))
{
$data = fread($file, $fsize);
}
else
{
while (!feof($file))
{
$data .= fread($file, 1024);
}
}
fclose($file);
}
return $data;
}
}
?>

That leads me to my next question...should I upgrade my PHP install, or just use this fix function? Is it worth upgrading because of this? I run a light traffic site which only uses php to do some forums and polls. I would consider that light use.

WhosAWhata

6:54 pm on Jun 18, 2004 (gmt 0)

10+ Year Member



in the long run it would probably be good to upgrade, if you don't want to however i would recommend making a page (something like functions.php) that contains your personal functions

example:
function nltobr($text){
return ereg_replace("\r\n","<br>",$text);
}
function add_header_and_footer($text){
return "My HTML Header".$text."My HTML Footer";
}