Current Location: Home> Latest Articles> How to Use PHP to Call Baidu Wenxin Yiyan API and Display Specific Sentences

How to Use PHP to Call Baidu Wenxin Yiyan API and Display Specific Sentences

gitbox 2025-06-12

1. Overview

This article explains how to use PHP to call the Baidu Wenxin Yiyan API to display specific types of sentences. We will provide a detailed guide on how to use the API and how to parse and display the returned data using PHP.

2. API Interface Description

2.1 Baidu Wenxin Yiyan API Introduction

The Baidu Wenxin Yiyan API offers various types of sentences, including famous quotes, poetry, and anime lines. By calling this API, you can retrieve sentences of specific types, making it both interesting and useful.

2.2 How to Use the API

To use this API, you need to make a request to the specified URL and specify the type of sentence you want to retrieve. The URL format for the request is as follows:


http://api.lwl12.com/hitokoto/v1.1/?encode=json&type=sentence_type&charset=utf-8
        

Parameters:

  • encode: Specifies the encoding of the returned result, it is recommended to use JSON.
  • type: Specifies the type of sentence, for example, "acg" for anime lines.
  • charset: Specifies the character set for the result, it is recommended to use UTF-8.

3. Implementing the API Call in PHP

3.1 Preparation

Before calling the API, we need to parse the JSON response to extract the sentence. The PHP function json_decode will help us with this task. Below is an example of how to parse the JSON data:


// Send request and get the JSON response from the API
$res = file_get_contents('http://api.lwl12.com/hitokoto/v1.1/?encode=json&type=acg&charset=utf-8');
// Parse the JSON data
$data = json_decode($res, true);
// Retrieve the sentence
$sentence = $data['hitokoto'];
        

3.2 Displaying the Sentence

Once we have the sentence from the API response, we can display it on the webpage. The display method can be customized based on your needs. Below is an example of a simple display code:


echo 'Sentence: ' . $sentence;
        

4. Complete Example Code

Below is the full PHP code example. You can copy and save it as a PHP file and run it to see the result:


// Send request and get the JSON response from the API
$res = file_get_contents('http://api.lwl12.com/hitokoto/v1.1/?encode=json&type=acg&charset=utf-8');
// Parse the JSON data
$data = json_decode($res, true);
// Retrieve the sentence
$sentence = $data['hitokoto'];
// Display the sentence
echo 'Sentence: ' . $sentence;
        

5. Conclusion

Through this guide, you have learned how to use PHP to call the Baidu Wenxin Yiyan API to retrieve and display specific types of sentences. You can further customize the display method based on your needs. We hope this article will be helpful in your development work.