Current Location: Home> Latest Articles> How to Implement Baidu Wenxin Yiyan API Using PHP: A Case Tutorial for Positive Quotes

How to Implement Baidu Wenxin Yiyan API Using PHP: A Case Tutorial for Positive Quotes

M66 2025-07-01

Introduction

Baidu Wenxin Yiyan is an API that provides random motivational, philosophical, poetic, and other quotes, aiming to bring positive energy and inspiration to users. In this article, we will implement the Baidu Wenxin Yiyan API using PHP, showing a detailed code example to help developers quickly integrate this functionality.

Steps to Implement

By following these steps, you can successfully implement the Baidu Wenxin Yiyan API in your PHP project:

Register a Baidu Developer Account

First, you need to visit the Baidu Developer Platform and register for a developer account. After registration, log in to your account, create a new application, and obtain the appid and appkey for the application.

Create the API Request Function

Create a function called apiRequest that accepts a URL as a parameter and sends a request to the specified URL to retrieve the response data.

Example Code

function apiRequest($url) {
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true
    ));
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}

Get a Random Quote

Create a function called getOneWord that does not accept any parameters. This function will call the apiRequest function to fetch a random quote from the API, then return the result in JSON format.

Example Code

function getOneWord() {
    $url = 'http://api.lwl12.com/hitokoto/main/get';
    $response = apiRequest($url);
    $result = json_decode($response);
    return $result->hitokoto;
}

Display the Quote

In the area where you want to display the quote, simply call the getOneWord function to retrieve and show the quote content.

Example Code

$oneWord = getOneWord();
echo $oneWord;

Conclusion

By following these steps, you can easily implement the Baidu Wenxin Yiyan API on your website or application. By calling this API, you can display random motivational, philosophical, poetic quotes, offering users positive energy. We hope this article provides valuable help to you.