Baidu Wenxin Yiyan offers an API that generates random content including classical poems, modern poetry, and famous quotes. This article will show you how to write a simple PHP program to call this API and retrieve a random quote.
Before using the Baidu Wenxin Yiyan API, you need to apply for an API Key. Visit the official Baidu Wenxin Yiyan website to register and generate your own API Key.
$url = 'https://v1.hitokoto.cn/'; // API endpoint
$key = ''; // Enter your API Key here
Please replace the $key variable with your own API Key.
After getting your API Key, you can use PHP’s cURL extension to send an HTTP GET request to the API, passing the API Key as a parameter.
$ch = curl_init(); // Initialize cURL handle
curl_setopt($ch, CURLOPT_URL, $url); // Set request URL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return result as string
$output = curl_exec($ch); // Execute request
curl_close($ch); // Close handle
This code initializes a cURL handle, configures the URL and response options, executes the request, and then closes the connection.
Once the request succeeds, you will receive a JSON response. Use json_decode() to parse it into an array, then extract the “hitokoto” field which contains the randomly generated quote.
$result = json_decode($output, true); // Parse JSON into array
$hitokoto = $result['hitokoto']; // Get random quote
$from = $result['from']; // Get source information
This allows easy access to the needed data fields.
Finally, output the retrieved quote to your webpage or application.
echo '' . $hitokoto . ''; // Display the quote
The echo statement outputs the quote to the client.
Here is the full PHP code combining all the above steps to call Baidu Wenxin Yiyan API:
$url = 'https://v1.hitokoto.cn/'; // API endpoint
$key = ''; // Enter your API Key here
<p>$ch = curl_init(); // Initialize cURL handle<br>
curl_setopt($ch, CURLOPT_URL, $url); // Set request URL<br>
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return response as string<br>
$output = curl_exec($ch); // Execute HTTP request<br>
curl_close($ch); // Close handle</p>
<p>$result = json_decode($output, true); // Decode JSON response<br>
$hitokoto = $result['hitokoto']; // Get random quote<br>
$from = $result['from']; // Get quote source</p>
<p>echo '' . $hitokoto . ''; // Output the quote<br>
This code allows easy integration of Baidu Wenxin Yiyan API to fetch and display a random sentence, ideal for websites or other PHP projects.