Baidu Wenxin Yiyan API is an API that provides random sentences in various categories, including animation, comics, games, novels, and original content. Each time the API is called, a random sentence is returned, suitable for use in personal blogs, websites, and other scenarios, offering a richer user experience.
To use the Baidu Wenxin Yiyan API, you first need to apply for the API Key on Baidu's Open Cloud Platform. The specific steps are as follows:
$api_key = 'your_api_key';
After obtaining the API Key, you can use PHP code to call the API. The specific steps are as follows:
$url = 'https://v1.hitokoto.cn'; $params = array( 'c' => '', 'encode' => 'json', 'charset' => 'utf-8', 'max_length' => 30 ); $response = file_get_contents($url . '?' . http_build_query($params)); $data = json_decode($response, true); if (isset($data['hitokoto'])) { $sentence = $data['hitokoto']; }
If you want to customize the sentences returned by the API or distribute the data to multiple sites, the following methods can help you achieve this.
Baidu Wenxin Yiyan API provides several parameters, allowing users to customize the returned data by specifying different parameters.
The parameter c specifies the category of the returned sentence, such as:
For example, if you want to get an animation sentence, you can set the parameter c to 'a':
$params = array( 'c' => 'a', 'encode' => 'json', 'charset' => 'utf-8', 'max_length' => 30 );
The parameter l specifies the length of the returned sentence, ranging from 1 to 200 characters. For example, if you want to get a sentence with a length of 20 characters, you can set the parameter l to 20:
$params = array( 'c' => '', 'encode' => 'json', 'charset' => 'utf-8', 'max_length' => 20 );
You can also create a custom API based on your needs to achieve data customization and distribution. The steps are as follows:
if ($_GET['type'] == 'hitokoto') { $params = array( 'c' => 'a', 'encode' => 'json', 'charset' => 'utf-8', 'max_length' => 30 ); $url = 'https://v1.hitokoto.cn?' . http_build_query($params); $data = json_decode(file_get_contents($url), true); echo $data['hitokoto']; }
For example, by visiting the following link, you can get an animation sentence:
http://your_site.com/your_api.php?type=hitokoto&c=a
By following the methods outlined above, you can customize and distribute data from the Baidu Wenxin Yiyan API, providing a more personalized experience for your users.