Build Your Own Hitokoto API
Introduction
Many websites like to add a hitokoto (a short quote or phrase) to their pages, but most of them call a third-party API. In fact, with the versatile PHP, you can achieve this feature with just a few lines of code.
Preparation
First, prepare a code editor, then create a new PHP file named api.php, and create another file named data.dat (both files must be encoded in UTF-8, otherwise you'll see garbled text).
Open data.dat and paste the text you want to display randomly, one entry per line. If you can't think of any good sentences right now, I've prepared dozens of NetEase Cloud Music hot comments here that you can download and use directly.
The Code
Copy and paste the following code into api.php and save it. Your very own "Hitokoto" API is now ready! Super simple, isn't it?
<?php
// File to store data
$filename = 'data.dat';
// Specify page encoding
header('Content-type: text/html; charset=utf-8');
if(!file_exists($filename)) {
die($filename . ' data file does not exist');
}
$data = array();
// Open the file
$fh = fopen($filename, 'r');
// Read line by line and store in array
while (!feof($fh)) {
$data[] = fgets($fh);
}
// Close the file
fclose($fh);
// Get a random line index
$result = $data[array_rand($data)];
echo $result;
The code above uses the fopen + fgets functions. Some people don't seem to like it much, thinking it's "inefficient." Don't worry, here's a version using the filegetcontents function:
<?php
// File to store data
$filename = 'data.dat';
// Specify page encoding
header('Content-type: text/html; charset=utf-8');
if(!file_exists($filename)) {
die($filename . ' data file does not exist');
}
// Read the entire data file
$data = file_get_contents($filename);
// Split into an array by newline
$data = explode(PHP_EOL, $data);
// Get a random line index
$result = $data[array_rand($data)];
// Remove extra newlines (just to be safe)
$result = str_replace(array("\r","\n","\r\n"), '', $result);
echo $result;
How to Reference It in a Static Page
The code above outputs a random sentence directly on the page. But how can you reference this API in a static webpage, just like you would with a hitokoto service?
It's simple. Replace the last line echo $result; with
echo 'document.write("'.htmlspecialchars($result).'");';
Then, at the desired location, include it using a JavaScript tag.
Example code:
<script src="http://your-domain.com/api.php"></script>