The Baidu Wenxin Yiyan API is widely used by developers to fetch random motivational or inspirational quotes. It provides an API that returns a random sentence, making it ideal for use as a quote or motivational statement at the footer of blogs or websites.
To use this API, simply send a GET request to the following URL to retrieve a random quote:
The API returns data in JSON format, like this:
{
"status": true,
"data": {
"id": "7742",
"hitokoto": "I've walked far into this dead-end alley of life, and now I can only walk downhill.",
"type": "a",
"from": "The Disappearance of Haruhi Suzumiya",
"from_who": "Yuki Nagato",
"creator": "XShow",
"creator_uid": 2886,
"reviewer": 0,
"uuid": "9cd04227-aa14-4df9-b8e0-6c0a5e4c6627",
"created_at": "1616677997"
}
}
The API provides the following optional parameters:
You can apply for an API key on the Baidu Wenxin API application page.
Here's an example of using PHP to call this API and retrieve a random quote:
In the code above, we define a function getHitokoto to send a request to the API and retrieve a quote. After calling the function, we fetch the quote and display it on the page.
Let’s look at how to use a PHP scheduled task manager to run the task every minute. We can use a CRON expression to set the schedule.
On a Linux system, you can edit the user’s scheduled tasks with the following command:
Then, you can set up a CRON expression to execute the task every minute:
In the above example, https://example.com/hitokoto.php is the actual URL of the PHP script you want to run.
Here's the PHP code for the scheduled task:
In this code, we first define the function getHitokoto to call the API and fetch the quote. We then save the quote to /var/www/html/wordpress/hitokoto.txt, which can be accessed later by your website. Finally, save this code on your server and set it to execute every minute using a CRON job.
This article covers the detailed steps of using PHP to integrate the Baidu Wenxin Yiyan API for scheduled task execution. By understanding the process, you can retrieve random quotes using the API and store them in a file or database. You can automate this process with a task scheduler, making it convenient and efficient.