banner
Magneto

Magnetoの小屋

Magneto在區塊鏈上の小屋,讓我們的文章在互聯網上永遠熠熠生輝!!

Self-built One Sentence API

Preface#

Many websites like to add a random quote on their pages, but they usually call a third-party API. In fact, using versatile PHP, this functionality can be achieved 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 should be encoded in UTF-8, otherwise there will be garbled text).

Open data.dat and paste the text you want to display randomly, one line per entry. If you can't think of any good sentences for now, I have prepared dozens of popular comments from NetEase Cloud Music, which you can download and use directly.

Writing the Code#

Copy and paste the following code into api.php and save it; your exclusive "random quote" API is now set up! Super simple, right...

<?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 document
$fh = fopen($filename, 'r');
// Read line by line and store in array
while (!feof($fh)) {
    $data[] = fgets($fh);
}
// Close the document
fclose($fh);
// Randomly get a line index
$result = $data[array_rand($data)];
echo $result;

The code above is implemented using fopen + fgets functions, which some friends seem to find not particularly favorable, thinking it is "inefficient." Don't worry, there's also a version implemented with the file_get_contents 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);
// Randomly get a line index
$result = $data[array_rand($data)];
// Remove extra newline characters (for safety)
$result = str_replace(array("\r","\n","\r\n"), '', $result);
echo $result;

How to reference it in a static page

The code above directly outputs a random sentence on the page. If you want to reference this API in a static webpage like a random quote, how can you achieve that?

It's simple, replace the last line echo $result; with

echo 'document.write("'.htmlspecialchars($result).'");';

Then you can call it using the method of including JS at the desired location.

Example code:

<script src="http://your-url/api.php"></script>

This article is synchronized and updated to xLog by Mix Space The original link is https://blog.fmcf.cc/posts/technology/Custom_Hitokoto_API

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.