Current Location: Home> Latest Articles> PHP uses Baidu Wenxin Yiyan API interface to realize the display of specific types of sentences

PHP uses Baidu Wenxin Yiyan API interface to realize the display of specific types of sentences

gitbox 2025-06-05

1. Project Overview

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.

2. Introduction to Baidu Wenxin Yiyan API interface

2.1 Interface function description

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.

2.2 Interface request format

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:

  • encode : Return format, it is recommended to use json
  • type : sentence type, for example, "acg" means anime sentences
  • charset : character set, it is recommended to use utf-8

3. Use PHP to make API calls

3.1 Get JSON data

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'];

3.2 Front-end display sentences

After getting the sentence, we can output it directly to the web page:

 
echo 'sentence:' . $sentence;

4. Complete sample code

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;

5. Summary

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.