Jump to content


Photo

select line from a file


  • Please log in to reply
8 replies to this topic

#1 superpimp

superpimp
  • Members
  • PipPip
  • Member
  • 24 posts

Posted 30 March 2006 - 06:06 PM

How do I select a line from a file? If I have a file like this:

hello
hi
test
etc...

I want to select like "hello" and "hi", ... as seperate text.

I tried this:

<?php
$file=file('file.txt');
$count=count($file);
$random=rand(0,$count);
echo $file[$random];
?>

but that doesnt work...

thx!

#2 ober

ober
  • Staff Alumni
  • Advanced Member
  • 5,337 posts
  • LocationEast Coast, USA

Posted 30 March 2006 - 06:47 PM

I think that's mostly correct, but you have to specify a path to the file.

Info: PHP Manual


#3 superpimp

superpimp
  • Members
  • PipPip
  • Member
  • 24 posts

Posted 30 March 2006 - 07:00 PM

Like file('c:\test\file.txt'); ?

#4 ober

ober
  • Staff Alumni
  • Advanced Member
  • 5,337 posts
  • LocationEast Coast, USA

Posted 30 March 2006 - 07:02 PM

Correct, but relative to your webserver... not the c drive.

Info: PHP Manual


#5 superpimp

superpimp
  • Members
  • PipPip
  • Member
  • 24 posts

Posted 30 March 2006 - 07:09 PM

well, the file is in the same path as then .php file, so actually I shouldn't specfy a path...

#6 ober

ober
  • Staff Alumni
  • Advanced Member
  • 5,337 posts
  • LocationEast Coast, USA

Posted 30 March 2006 - 07:49 PM

$file=file('test.txt');
$count=count($file);
$random=rand(0,$count-1);
echo $file[$random];

Color me wrong... you don't have to specify a path.

The above works for me.

Info: PHP Manual


#7 superpimp

superpimp
  • Members
  • PipPip
  • Member
  • 24 posts

Posted 01 April 2006 - 11:26 AM

well, it sucks. that doesnt work. its very weird, i've added extra things, that work in other scripts but they wont work here, grrr. I even tried your code, doenst work either :(

$file=file('test.txt');
$file2=file_get_contents("test.txt");
$filecontents = file_get_contents("test.txt");
$count=count($file);
$random=rand(0,$count-1);
echo $file[$random];
echo $file2;
echo $filecontents;

this gives a blank screen :( What am I doing wrong???

edit: THANKS, I found the error :)

#8 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 01 April 2006 - 03:55 PM

You're code looks fine. What's in the file?

Ken

#9 superpimp

superpimp
  • Members
  • PipPip
  • Member
  • 24 posts

Posted 01 April 2006 - 04:05 PM

the problem was I opened with <? instead of <?php
stupid mistake...




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users