Build a Simple Random-Quote API With PHP

XMLans Posted on 2025-07-20 17 Views


A random-quote API can be a small first web project: put a few lines of text in a file, choose one on each request, and return it. The original article linked my quote endpoint as an example; its availability is separate from the tutorial.

Prepare the server

Use a currently supported PHP release behind a web server such as Nginx. The old article used PHP 7.4, which should not be your choice for a new installation. Put index.php and a UTF-8 yiyan.txt file in the application directory.

index.php

This adapted example handles an empty source file, uses a correct response content type, and safely serializes text for the optional JavaScript format. It avoids the original document.write string-concatenation approach.

<?php
declare(strict_types=1);
header('X-Content-Type-Options: nosniff');
header('Cache-Control: no-store');
$lines = file(__DIR__ . '/yiyan.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ($lines === false || count($lines) === 0) {
    http_response_code(503);
    header('Content-Type: text/plain; charset=utf-8');
    exit('No quotes available.');
}
$text = trim($lines[random_int(0, count($lines) - 1)]);
$format = $_GET['format'] ?? 'text';
$json = json_encode($text, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_THROW_ON_ERROR);
if ($format === 'json') {
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['text' => $text], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
} elseif ($format === 'js') {
    header('Content-Type: application/javascript; charset=utf-8');
    echo 'window.hitokoto = function (target) { const text = ' . $json . '; if (target) target.textContent = text; return text; };';
} else {
    header('Content-Type: text/plain; charset=utf-8');
    echo $text;
}

yiyan.txt

Write one quote per line. For example:

A small step is still a step.
Keep learning, one question at a time.
Build something simple, then improve it.

Try the response formats

Visit your configured hostname for plain text. Use ?format=json for a JSON object, or ?format=js for the optional script response. The original prose said encode=js even though its code expected format; this version uses format consistently.

https://quotes.example.com/
https://quotes.example.com/?format=json
https://quotes.example.com/?format=js

For the script format, window.hitokoto(element) writes the quote into that element using textContent, or window.hitokoto() returns it. JSON is usually easier for a new integration. Serving text as data also avoids treating a quote containing markup as HTML.

The sample sends no-store so refreshes can select a new quote. Caching an API is not inherently wrong: choose a policy that matches whether you want a fresh result or a stable response. Set reasonable request limits at the web server or proxy if the endpoint is public. For a larger collection, a database and explicit categories can replace the text file.

Adapted from the original Chinese article, published on July 20, 2025.

Hi! I frequently update with various articles about technology, practical tips, and cutting-edge news. I hope it will be helpful to you!
Last updated on 2026-09-30