0

I’m making a random sentence generator for my English class. I’m close but because of my limited php and javascript knowledge I need to ask for help. I’m not bad at reading the code, I just get stuck writing it.

I want to use explode to break up a string of comma seperated values. The string is a mix of English and Spanish, on the .txt file they would seperated like:

The book, El libro
The man, El hombre
The woman, La mujer

etc.

I would like to break these two values into an array and display them in separate places on my web page. I`m going to use a random text generator script that I found, it’s working great with no problems. I just need to modify it using explode to read, separate the values into an array, and be able to display the separate values of the array.

<?php

/* File, where the random text/quotes are stored one per line */
$settings['text_from_file'] = 'quotes.txt';

/*
How to display the text?
0 = raw mode: print the text as it is, when using RanTex as an include
1 = Javascript mode: when using Javascript to display the quote
*/
$settings['display_type'] = 1;

/* Allow on-the-fly settings override? 0 = NO, 1 = YES */
$settings['allow_otf'] = 1;

// Override type?
if ($settings['allow_otf'] && isset($_GET['type']))
{
$type = intval($_GET['type']);
}
else
{
$type = $settings['display_type'];
}

 // Get a list of all text options
if ($settings['text_from_file'])
{
$settings['quotes'] = file($settings['text_from_file']);
}

// If we have any text choose a random one, otherwise show 'No text to                              choose from'
if (count($settings['quotes']))
{
$txt = $settings['quotes'][array_rand($settings['quotes'])];
}
else
{
$txt = 'No text to choose from';
 }

// Output the image according to the selected type
if ($type)
{
// New lines will break Javascript, remove any and replace them with <br />
$txt = nl2br(trim($txt));
$txt = str_replace(array("\n","\r"),'',$txt);

// Set the correct MIME type
header("Content-type: text/javascript");

// Print the Javascript code
echo 'document.write(\''.addslashes($txt).'\')';
}
else
{
echo $txt;
}
?>

The script that displays the result:

 <script type="text/javascript" src="rantex.php?type=1"></script>

Can someone please help me modify the rantex.php file so that I can use explode to separate the different comma separated values, and use a different script to call them in different places on my web page?

Thank you, and please excuse my noobness.

3 Answers 3

0

The following seems unnecessary, since file() will have already removed new line characters:

// New lines will break Javascript, remove any and replace them with <br />
$txt = nl2br(trim($txt));
$txt = str_replace(array("\n","\r"),'',$txt);

To break your line, you may instead use:

list($english, $spanish) = explode(', ', trim($txt));
8
  • I hope I'm reading the code right. If this splits the $txt value into $english $spanish values, how can I separate them with different JavaScripts? I know I can use the stock <script type="text/javascript" src="rantex.php?type=1"></script> but no for two different placements on my web page. Thanks
    – nycdude
    Jan 25, 2015 at 18:03
  • Durning testing using your approach I was able to call the $english value but not the $spanish value. I tried using this: echo 'document.write(\''.addslashes($english).'\')'; echo 'document.write(\''.addslashes($spanish).'\')'; } else { echo $txt; } That's a bit not right, right?
    – nycdude
    Jan 25, 2015 at 19:13
  • The script supposes that each line is separated by a comma followed by a space.
    – BeS
    Jan 25, 2015 at 21:59
  • Not clear what you want to achieve by calling twice the script. If you want to write to two different places in the HTML, try using:echo 'document.getElementById('id1').innerHtml = \''+addslashes($english)+'\'
    – BeS
    Jan 25, 2015 at 22:06
  • Yeah I saw the extra space later but I am still jammed up. Yea no I don't want to call on it twice but I do need to somehow do the logic on a .PHP and call the $english and $spanish variables separately with some JavaScript on a static HTML page.Thanks for your help
    – nycdude
    Jan 25, 2015 at 23:06
0

It seems you are trying to use PHP to serve a static page with some random sentences, right? So why not use PHP to serve valid JSON, and handle to display logic on the client?

Heres a quick implementation.

// Get the data from the text file
$source = file_get_contents('./quotes.txt', true);

// Build an array (break on every line break)                           
$sentences = explode("\n", $source);

// Filter out empty values (if there is any)
$filtered = array_filter($sentences, function($item) { 
  return $item !== "";
});

// Build a hashmap of the array
$pairs = array_map(function($item) { 
  return ['sentence' => $item];
}, $filtered);

// Encode the hashmap to JSON, and return this to the client.
$json = json_encode($pairs);

Now you can let the client handle the rest, with some basic JavaScript.

// Return a random sentence from your list.
var random = sentences[Math.floor(Math.random() * sentences.length)];

// Finally display it
random.sentence

[edit]

You can get the JSON data to client in many ways, but if you don't want to use something like Ajax, you could simply just dump the contents on your webpage, then use JavaScript to update the random sentence, from the global window object.

// Inside your php page

<p>English: <span id="english"></span></p>
<p>Spanish: <span id="spanish"></span></p>

<script>

  var sentences = <?= json_encode($pairs); ?>;
  var random = sentences[Math.floor(Math.random() * sentences.length)];

  var elspa = document.getElementById('spanish');
  var eleng = document.getElementById('english');

  elspa.innerText = random.sentence.split(',')[1];
  eleng.innerText = random.sentence.split(',')[0];

</script>
12
  • The random generator I'm using does use PHP to process the logic and I can use either JavaScript or PHP on my static web page. I am interested in trying out the method you suggest, though I`m not sure how to implement it. I hate asking to be hand-held but can you suggest please how I can call these values to my web page? Thanks for your attention
    – nycdude
    Jan 25, 2015 at 18:17
  • Well, its quite hard not knowing the rest of your setup, but basically just get a hold of the path where the .txt file is, and use the above methods to parse the file. If you are using vanilla PHP and HTML mixed you could just echo the result in your page and grab it with JavaScript from the window object. If you have some kind of MVC setup you could return the JSON from your controller, and even get the JSON content via an AJAX call.
    – pat
    Jan 25, 2015 at 18:30
  • Yes sorry, I am using DW CS6 and the latest MAMP for testing. When the site is ready I will get the appropriate hosting to handle my needs, so I'm open to the best format. The method you suggest seems much more efficient than the script I found online, I can read it and see where it's going but I`m not sure what the JavaScript on my web page would look like. It's currently using <script type="text/javascript" src="rantex.php?type=1"></script> for the one value. Thank you.
    – nycdude
    Jan 25, 2015 at 18:48
  • Edited my answer. Ill hope it will help.
    – pat
    Jan 25, 2015 at 18:54
  • Yes, it's helping a lot thanks. I think there is a misunderstanding and it's my fault for not seeing it sooner. Yes I do want to generate random sentences but I need more control. When I generate some random words I need to have their Spanish meanings connected to that I can display it under the English words. The plan is to have a text file with a list of two values separated with a comma: The book,El libro etc. The randomness is needed to get the given random line but I need to parse them at the comma so I have an english value and a spanish value that i can display separately. Thanks again
    – nycdude
    Jan 25, 2015 at 19:25
0

Ok, so I have this figured out, I take 0 credit because I paid someone to do it. Special thanks to @stormpat for sending me in the right direction, if not for him I wouldn't have looked at this from a JSON point of view.

The .PHP file is like so:

<?php
$f_contents = file('quotes.txt'); 
$line = trim($f_contents[rand(0, count($f_contents) - 1)]);
$data = explode(',', $line);
$data['eng'] = $data[0];
$data['esp'] = $data[1];

echo json_encode($data);
?>

On the .HTML page in the header:

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script>
    (function ($) {
        $(function()
        {
            function load_random_data() {
                $.get('random_line.php', function(data) {
                    var data = $.parseJSON(data);
                    $('#random_english').text(data.eng);
                    $('#random_spanish').text(data.esp);
                });
            }
            load_random_data();
            $('#get_random').click(function(e){
                e.preventDefault();
                load_random_data();
            });


        });
    })(jQuery);
    </script>

This splits the different variables into classes, so to call them into my html page I call them by their class, for instance I wanted to drop the variable into a table cell so I gave the individual td cell a class:

                <td id="random_spanish"></td>
                <td id="random_english"></td>

Plus as a bonus the coder threw in a nifty button to refresh the json classes:

<input type="button" value="Get random" id="get_random" />

So now I don`t have to have my students refresh the whole web page, they can just hit the button and refresh the random variables.

Thanks again everyone!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.