Current Location: Home> Latest Articles> How to Integrate Baidu Wenxin Yiyan API in PHP to Fetch Random Quotes

How to Integrate Baidu Wenxin Yiyan API in PHP to Fetch Random Quotes

M66 2025-07-11

Introduction

Baidu Wenxin Yiyan API is an interface that provides randomly generated quotes. It is simple to integrate into your project. This article will guide you through the process of connecting the Baidu Wenxin Yiyan API using PHP, showcasing how to send an HTTP request with PHP's cURL library to retrieve the data from the API.

Apply for API Access

First, you need to apply for access to the Baidu Wenxin Yiyan API. Log in to the Baidu Open Platform, create an application, and obtain your API Key.

PHP Code Implementation

Next, we will use PHP's cURL library to send an HTTP request and fetch data from the Baidu Wenxin Yiyan API. Below is the PHP code example for this functionality:

function getBaiduWenxinYiyan($apiKey) {
    $url = 'http://api.lwl12.com/hitokoto/main/get?key=' . $apiKey;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

In the code above, we first construct the request URL by appending the API Key. Then, we use cURL to send the request and get the response. Afterward, we close the cURL session and return the result.

Calling the API to Get a Quote

You can call the function and output the fetched quote as shown below:

$apiKey = 'your_api_key';
$result = getBaiduWenxinYiyan($apiKey);
echo $result;

In this example, replace the default API Key with your own and call the function to display the result in your browser.

Parsing and Processing the Returned Data

The returned data is usually in JSON format, which can be parsed using PHP's json_decode() function. Here is an example of how to extract the quote and source from the API response:

$apiKey = 'your_api_key';
$result = getBaiduWenxinYiyan($apiKey);
$data = json_decode($result, true);
if ($data && isset($data['hitokoto']) && isset($data['from'])) {
    $sentence = $data['hitokoto'];
    $source = $data['from'];
    echo "Quote: {$sentence}<br>";
    echo "Source: {$source}<br>";
} else {
    echo "Failed to get a quote.";

In this code, we parse the JSON response into a PHP array, check if the data is valid, and extract the quote and source. If the quote retrieval fails, we display an error message.

Conclusion

By following these steps, you can easily integrate Baidu Wenxin Yiyan API into PHP and get random quotes. This can be useful for personal websites, blogs, and other content-generation scenarios. We hope this article helps you integrate the API into your project smoothly.