In PHP project development, many application scenarios require dynamically obtaining sentences for page decoration, personalized signatures or copywriting display. This article will introduce in detail how to call Baidu Wenxin Yiyan API through PHP language to achieve the process of obtaining and displaying sentences of specified types.
Baidu Wenxin Yiyan API supports returning various types of sentences, such as famous quotes, ancient poems, animation lines, etc. Users only need to specify the corresponding type parameters in the request URL to obtain the corresponding content, which is very suitable for content display applications.
We use URLs in the following format to call the API:
http://api.lwl12.com/hitokoto/v1.1/?encode=json&type=Sentence Type&charset=utf-8
Parameter description:
First, we use PHP's file_get_contents method to request API data, and then parse the returned JSON data through json_decode to obtain the sentence content.
// Send a request and getAPIReturnedJSONdata
$res = file_get_contents('http://api.lwl12.com/hitokoto/v1.1/?encode=json&type=acg&charset=utf-8');
// AnalysisJSONdata
$data = json_decode($res, true);
// Extract sentence content
$sentence = $data['hitokoto'];
After getting the sentence, we can output it directly to the web page:
echo 'sentence:' . $sentence;
The following is the complete PHP sample code, copy it to a local file and run it to experience it:
// Send a request and getAPIReturnedJSONdata
$res = file_get_contents('http://api.lwl12.com/hitokoto/v1.1/?encode=json&type=acg&charset=utf-8');
// AnalysisJSONdata
$data = json_decode($res, true);
// Extract sentence content
$sentence = $data['hitokoto'];
// 输出sentence
echo 'sentence:' . $sentence;
Through the examples and explanations of this article, we learned how to use PHP to call Baidu Wenxin Yiyan API interface, obtain various sentences as needed and display them on the web page. This method is suitable for various application scenarios such as personalized content display and emotional copy recommendation. If you are looking for a lightweight and practical text content solution, try integrating this API.