Jump to content


Photo

read random line from a text file.


  • Please log in to reply
3 replies to this topic

#1 jasonc

jasonc
  • Members
  • PipPipPip
  • Advanced Member
  • 841 posts

Posted 18 April 2006 - 10:04 PM

I have a large file with a list of songs, i wish to chose at random 5 of these to be shown on my web page.

the problem i have is reading this file to get the info from it.

i have the php script that randomise 5 numbers all i need is to know how to extract the lets say

the 5, 17, 26, 55, 105 and er 300 th lines from a text (tracks.txt) file.

I known in the past that scripts can write a file but how can i read a line from one?

also been told be a friend that when i do this i also need to be sure that the file can be read many time at the same time.

I was going to use my database but decided against that as i have had problems in the past with them.
also adding the data to it would take ages too.

thank you in advance for your help.

#2 ypirc

ypirc
  • Members
  • PipPipPip
  • Advanced Member
  • 54 posts

Posted 18 April 2006 - 10:14 PM

This is what I came up with. There are a several solutions.

*** Came up with a different solution than before...
<?
$file = file('/etc/passwd');
shuffle($file);

for($i=0;$i<5;$i++) printf("%s\n", trim($file[$i]));
?>


#3 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,021 posts

Posted 18 April 2006 - 10:22 PM

[!--quoteo--][div class=\'quotetop\']QUOTE[/div][div class=\'quotemain\'][!--quotec--]I was going to use my database ... adding the data to it would take ages too.[/quote]

why, if you already have the data in a text file?


Try

$songs = file('songlist.txt');

$rand_titles = array_rand($songs, 5);

foreach ($rand_titles as $k) {
          echo $songs[$k], '<br />';
}

If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts

#4 jasonc

jasonc
  • Members
  • PipPipPip
  • Advanced Member
  • 841 posts

Posted 19 April 2006 - 10:03 AM

thank you very much for your help, this worked a treat. i now have a new command to play around with and get to know.

J


[!--quoteo(post=366218:date=Apr 18 2006, 11:22 PM:name=Barand)--][div class=\'quotetop\']QUOTE(Barand @ Apr 18 2006, 11:22 PM) View Post[/div][div class=\'quotemain\'][!--quotec--]
why, if you already have the data in a text file?
Try

$songs = file('songlist.txt');

$rand_titles = array_rand($songs, 5);

foreach ($rand_titles as $k) {
          echo $songs[$k], '<br />';
}
[/quote]





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users