1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

How to fill a textspace with random data from a text file

Discussion in 'Web Design' started by dragosdydy, May 11, 2013.

  1. dragosdydy

    dragosdydy Junior Member

    Joined:
    Jan 23, 2012
    Messages:
    116
    Likes Received:
    49
    Location:
    Italy
    Hello guys. I'm working on a HTML website and I'm wondering if there's any way to get random data from a TextFile and fill a TextBox with it.
    This is what i want:

    I have a .txt file with the following lines:

    This is my 1st line of the text
    This is my 2nd line of the text
    This is my 3rd line of the text
    This is my 4th line of the text
    This is my 6th line of the text
    This is my 7th line of the text


    And then i have a HTML file with one TextBox. When the page loads, the text box will be filled with one random line from the .txt file.

    Is there any way to do that with HTML or JavaScript? Thanks a lot.
     
  2. DeJohn

    DeJohn Newbie

    Joined:
    Nov 10, 2012
    Messages:
    41
    Likes Received:
    16
    Home Page:
    You can do this if you make your page as .php , add the folowing code:

    Code:
    $f_contents = file("file.txt");
    $line = $f_contents[array_rand($f_contents)];
    $data = $line;
    
    and echo $data in your textbox

    When the page will be loaded it will automatically get a random line of your text file and add to your textbox.

    Let me know if is ok for you or need to do this using JavaScript and HTML only.
     
    • Thanks Thanks x 1
  3. dragosdydy

    dragosdydy Junior Member

    Joined:
    Jan 23, 2012
    Messages:
    116
    Likes Received:
    49
    Location:
    Italy
    Yea! Thanks a lot! It works great. I've inserted the code into HTML file as i wrote below, and then saved the file to .php and everything's OK! Thank you very much!

    Code:
    <?PHP
    $f_contents = file("file.txt");
    $line = $f_contents[array_rand($f_contents)];
    $data = $line;
    ?>
    

    Code:
    <?php echo $data; ?>
     
  4. DeJohn

    DeJohn Newbie

    Joined:
    Nov 10, 2012
    Messages:
    41
    Likes Received:
    16
    Home Page:
    I am happy to know that it's ok for you, you can handle files easier with PHP.