Support » Fixing WordPress » Code for calling and randomizing contents of a .txt?

  • Resolved HopefulGJL

    (@hopefulgjl)


    Hello,

    I am looking to call the contents of a .txt document and randomize those contents.

    I think I found the php code that might work. Would something like this be correct?

    $f_contents = file("TheRandomContent.txt");
    print_r($f_contents);
    //$line = $f_contents[array_rand($f_contents)];
    //echo $line;

    If that is correct, then how can I alter it to call the document if it’s located say here:

    <src="http://TheWebSite.com/wp-content/uploads/2012/07/TheRandomContent.txt"

    Am I on the right track here?

    And, if so, how can I incorporate this in to the first code I listed? I’m a real beginner, so I’m kindly asking for specifics, please.

    Thanks in advance for your help!

Viewing 3 replies - 1 through 3 (of 3 total)
  • s_ha_dum

    (@apljdi)

    file should work. The docs have an example for reading from a web address.

    You could also use fopen or curl.

    I have found my answer here in those post, which led to this site containing the answer.

    For ease, I’m re-posting that code here:

    <?php
    	$file  = "/home/public_html/path/to/random-quotes.txt";
    	$quote = file($file);
    	echo $quote[array_rand($quote)];
    ?>

    With this solution, you upload your text file to your file manager, and then put your pathway to that text file in place of the one above.

    Thanks for the info everyone!

    P.S. Even though that code basically has “quote” in it, it also works for other things, like banner ads. Even if it’s not the “best” solution, it is working.

    Oh yeah, I also found this solution, but it does not call from a text file though so you’d have to have everything you want to randomize directly in your php file.

    If anyone is looking to alter this slightly for height around the quotes, or padding, etc., please review this thread here.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Code for calling and randomizing contents of a .txt?’ is closed to new replies.