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

How to Call Baidu Wenxin Yiyan API in PHP to Get Random Quotes

M66 2025-07-15

Overview

PHP is a powerful server-side scripting language widely used in web development. The Baidu Wenxin Yiyan API offers a convenient way to get random quotes or text, which is ideal for website quote displays or page decorations. This article will walk you through how to use PHP to call the Baidu Wenxin Yiyan API and retrieve random text.

Creating a Baidu Developer Application

Before using the Baidu Wenxin Yiyan API, you need to create an application in the Baidu Developer Center and obtain an API Key. The steps are as follows:

  • Visit the Baidu Developer Center
  • Log in, click on the top-right “Console”, and select “Create Application”
  • Select “API Call” and click “Create Now”
  • Fill out the application’s basic information and submit it
  • After successful creation, go to the application details page to find the API Key

PHP Code Implementation

Once you have your API Key, you can start writing PHP code to call the Baidu Wenxin Yiyan API. Here’s an example:

<?php<br>// Configure the API Key<br>$apiKey = "your_api_key"; // Replace with your actual API Key<br><br>// Request API URL<br>$url = "http://api.lwl12.com/hitokoto/main/get";<br><br>// Construct the request parameters<br>$params = [<br>    "encode" => "json",<br>    "charset" => "utf-8",<br>    "apiKey" => $apiKey,<br>];<br><br>// Build the request URL<br>$requestUrl = $url . "?" . http_build_query($params);<br><br>// Send HTTP request<br>$response = file_get_contents($requestUrl);<br><br>// Parse the API response<br>$data = json_decode($response, true);<br><br>// Get the random text<br>if ($data && isset($data["content"])) {<br>    $content = $data["content"];<br>    echo "Random Quote: " . $content;<br>} else {<br>    echo "Failed to retrieve random quote";<br>}<br>?>

In the code, first replace `your_api_key` with the actual API Key obtained from the Baidu Developer Center. Then, we construct the request URL and append the request parameters. We use the `file_get_contents` function to send the HTTP request, get the API response, and parse the returned JSON data. Finally, we extract the random quote from the response and display it.

Application Example

You can display the retrieved random text as needed. For example, the random text can be shown on your website page or stored in a database for future use. This way, your website will offer dynamic and creative content.

Conclusion

Through this article, we’ve learned how to call the Baidu Wenxin Yiyan API in PHP to retrieve random quotes and display them. By configuring the API Key, constructing request parameters, sending HTTP requests, and parsing the response, you can easily implement this functionality. I hope this article helps you when integrating PHP with the Baidu Wenxin Yiyan API.