In website development, dynamic sentence displays are a common feature. For example, daily quotes or inspirational sayings on the homepage. Such sentences not only enhance interactivity but also improve user engagement. Baidu's Wenxin Yiyan API provides a rich set of random quotes, covering various fields like anime, games, novels, and more, allowing users to choose the type of quote they need.
The interface URL for the Baidu Wenxin Yiyan API is: https://v1.hitokoto.cn/. This API supports several parameters, making it flexible for users to fetch various types of sentences.
The c parameter specifies the type of sentence. Below are the available options:
For example, if you want to fetch sentences related to anime, you should set the c parameter to "ac".
This parameter specifies the encoding format of the returned sentence. The default value is UTF-8.
It specifies the character set for the returned sentences, such as UTF-8, GBK, GB2312, GB18030, etc.
This parameter specifies the maximum length of the sentence to return. For instance, length=5 will return a sentence with no more than 5 characters.
This ensures the integrity of the API's response, preventing data tampering.
The API service provider includes an acknowledgment message in the response. Free users can make up to 1000 requests per day, and anything beyond that will require payment.
Here is a simple PHP implementation that shows a random quote on your webpage:
In the above code, we first set the sentence type to "anime". Then, we use the curl function to send an HTTP request to get the API response, and we decode the response into an array format. Finally, we output the random sentence on the webpage.
Besides PHP, JavaScript can also be used to implement random sentence display. Here is a simple JavaScript example:
In this example, we specify the sentence type as "internet slang". Then we use the fetch method to send a request to the API, retrieve the JSON data, and fill the random sentence into a specified HTML element.
This article introduced how to implement dynamic sentence display on your webpage using Baidu's Wenxin Yiyan API. Whether using PHP or JavaScript, the API allows easy integration for displaying random quotes from various fields. By adjusting API parameters, you can customize the sentence types, enhancing website content and interactivity.