Skip to content

Instantly share code, notes, and snippets.

@drakakisgeo
Created October 11, 2012 18:54
Show Gist options
  • Save drakakisgeo/3874690 to your computer and use it in GitHub Desktop.
Save drakakisgeo/3874690 to your computer and use it in GitHub Desktop.
Random quote without DB from a csv file
<?php
/*
----FEATURES----
1. DOESN'T NEED A DATABASE
2. EASY TO SHARE WITH ANYBODY - ITS JUST A CSV FILE SO MANY PEOPLE CAN GIVE YOU QUOTES!
3. STRIPS ANY PROBLEMATIC CHARACTER SO YOU CAN PLAY WITH YOUR OWN QUOTE SYMBOLS ( VIA CSS)
4. CAN STYLE IT BY CSS
5. THE CODE PRODUCED IS SIMPLE HTML. ITS SUPER FAST.
----HOW TO USE THIS----
1. CREATE current.txt and parsed.txt in the same directory as this file
2. RUN A CRON JOB THAT EXECUTES THIS SCRIPT WHEN EVER YOU LIKE
3. THEN run A SIMPLE file_get_contents("YOUR ROOT PATH/current.php") WHERE EVER YOU WANT IT IN YOUR HTML PAGE
4. CUSTOMIZE THE LOOKS BY CSS ( .gmsg, .qauthor)
IMPORTANT INFO: The csv file must use comma delimiter and "" for values. Only Three columns are needed. No,Quote,Author.
The First line can use those titles and then the quotes and info must follow.
Its crucial to have the No column in order for this to work.
*/
function convertCSVtoAssocMArray($file, $delimiter)
{
$result = Array();
$size = filesize($file) +1;
$file = fopen($file, 'r');
$keys = fgetcsv($file, $size, $delimiter);
while ($row = fgetcsv($file, $size, $delimiter))
{
$result[] = $row;
}
fclose($file);
return $result;
}
// get quotes
$quotes = convertCSVtoAssocMArray("quotes.csv",",");
$filename = "parsed.txt";
# retrieve from file
$parsed = unserialize(file_get_contents($filename));
if(!$parsed) $parsed = array();
$allquotes = sizeof($quotes);
if($allquotes>sizeof($parsed)){
do{
$randomid = array_rand($quotes);
}while(in_array($randomid,$parsed));
# save it to file
$parsed[] = $randomid;
$fp = fopen($filename, 'w+') or die("I could not open $filename.");
fwrite($fp, serialize($parsed));
fclose($fp);
}else{
$parsed = array();
$randomid = array_rand($quotes);
$parsed[]=$randomid;
$fp = fopen($filename, 'w+') or die("I could not open $filename.");
fwrite($fp, serialize($parsed));
fclose($fp);
}
$quotemsg = $quotes[$randomid][0]; // quote
echo "<br>".$quotemsg."<br>";
// clear quote from invalid characters
$quotemsg = str_replace("\"","",$quotemsg);
$quotemsg = str_replace("“","",$quotemsg);
$quotemsg = str_replace("”","",$quotemsg);
$quotemsg = str_replace("`","",$quotemsg);
$quotemsg = str_replace("«","",$quotemsg);
$quotemsg = str_replace("»","",$quotemsg);
$string = "<div class=\"qmsg\">".trim($quotemsg)."</div>";
$string.= "<div class=\"qauthor\">".trim($quotes[$randomid][1])."</div>";
// store in the current file
$fp = fopen("current.txt", 'w+') or die("I could not open $filename.");
fwrite($fp, $string);
fclose($fp);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment