jimmyhumbled Posted October 22, 2008 Share Posted October 22, 2008 Hello - this is my first post here but after looking round it looks like a handy place to know about. I am new to PHP and have been struggling with a script. The working idea is to pull in at random a link from a plain text file and show it on my website. The code is as follows: <?php $adfile = "url.txt"; $ads = array(); $fh = fopen($adfile, "r"); while(!feof($fh)) { $line = fgets($fh, 10240); $line = trim($line); if($line != "") { $ads[] = $line; } } $num = count($ads); $idx = rand(0, $num-1); echo $ads[$idx]; ?> The text file is set out with a new link on each line as follows <a href="www.link1.com">The text link</a> <a href="www.link2.com">The text link</a> etc for 10 lines Everything seems to work but about 1/2 the the link is not pulled in at all and the script makes the next line down on the page a link that doesnt go anywhere, I wondered if anyone would have time to have a scan of the above and let me know if they could see what might be wrong, Thanks Link to comment https://forums.phpfreaks.com/topic/129664-pulling-in-a-line-of-text-i-get-an-error-every-3rd-use/ Share on other sites More sharing options...
trq Posted October 22, 2008 Share Posted October 22, 2008 You can get rid of most of that code for starters: <?php $file = file('url.txt'); echo $file[rand(0,count($file)-1)]; ?> Can you show us the html this produces? Link to comment https://forums.phpfreaks.com/topic/129664-pulling-in-a-line-of-text-i-get-an-error-every-3rd-use/#findComment-672288 Share on other sites More sharing options...
philipolson Posted October 22, 2008 Share Posted October 22, 2008 And consider passing FILE_SKIP_EMPTY_LINES into file(). Link to comment https://forums.phpfreaks.com/topic/129664-pulling-in-a-line-of-text-i-get-an-error-every-3rd-use/#findComment-672291 Share on other sites More sharing options...
Barand Posted October 22, 2008 Share Posted October 22, 2008 couldn't spot an obvious reason but you could just do <?php $adfile = "url.txt"; $ads = file($adfile); echo $ads[array_rand($ads)]; ?> Link to comment https://forums.phpfreaks.com/topic/129664-pulling-in-a-line-of-text-i-get-an-error-every-3rd-use/#findComment-672292 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.