Getting an arbitrary row from a flat text file database

I am wondering if the following php script can be specified in Javascript (or HTML5)? Basically this is a simple file with reading .txt and displaying a random line on it:

<?php
$text = file_get_contents('flatFileDB.txt');
$textArray = explode("\n", $text);
$randArrayIndexNum = array_rand($textArray);
$randPhrase = $textArray[$randArrayIndexNum];
?>
<html>
<body>
<h2><?php echo $randPhrase; ?></h2>
</body>
</html>

Example 'flatFileDB.txt':

Line 1
Line 2
Line 3
Line 4
Line 5
...
...
etc

An example is taken here: http://www.developphp.com/view.php?tid=1213 , and I would like to do the same, but without server-side php. Is it possible?

+3
source share
1 answer

Assuming you can access the flat file file in http://www.example.com/flatFileDB.txt, and your HTML file has a div with an identification value random-phrase:

var request = new XMLHttpRequest();
request.onload = function() {
    // get the file contents
    var fileContent = this.responseText;
    // split into lines
    var fileContentLines = fileContent.split( '\n' );
    // get a random index (line number)
    var randomLineIndex = Math.floor( Math.random() * fileContentLines.length );
    // extract the value
    var randomLine = fileContentLines[ randomLineIndex ];

    // add the random line in a div
    document.getElementById( 'random-phrase' ).innerHTML = randomLine;
};
request.open( 'GET', 'http://www.example.com/flatFileDB.txt', true );
request.send();

XMLHttpRequest, .

+2

All Articles