Baidu Wenxin Yiyan offers an open API that returns a variety of random sentences, including humorous, inspirational, and philosophical content. This article demonstrates how to use PHP to fetch data from this API and format it for easier display and use.
First, confirm the API URL address. Here is an example:
<span class="fun">$url = 'https://v1.hitokoto.cn';</span>
Use PHP's file_get_contents() function to read the API response, then convert the JSON data into a PHP array with json_decode(). Example code:
$data = file_get_contents($url);
$data = json_decode($data, true);
This way, you obtain an associative array containing the API data, ready for further processing.
To prevent any HTML tags in the API response from affecting page display, use htmlspecialchars() to escape the sentence content:
<span class="fun">$content = htmlspecialchars($data['hitokoto']);</span>
The source of the sentence may also contain special characters and should be escaped similarly:
<span class="fun">$source = htmlspecialchars($data['from']);</span>
Some sentences include author info. Use isset() to check if the author field exists, then format it accordingly:
$author = '';
if (isset($data['creator'])) {
$author = htmlspecialchars($data['creator']);
}
After formatting, you can output the content, source, and author information as follows:
echo $content;
echo $source;
echo $author;
You can place these outputs anywhere on your webpage or integrate them into other business logic as needed.
This article showed how to retrieve and process random sentences from the Baidu Wenxin Yiyan API using PHP. We used file_get_contents() to fetch JSON data, json_decode() to convert it into an array, and htmlspecialchars() to escape the content, source, and author fields, avoiding display issues caused by HTML tags. This straightforward approach makes it easy to use and display API data in your projects.