Adding random quote features to a website is a great way to increase engagement and visual appeal. The Baidu Wenxin Yiyan API provides a simple interface for retrieving random sentences. This article demonstrates how to call the API using PHP and store the result in a database.
First, create a developer account on Baidu Cloud and register a Wenxin Yiyan application. Once created, you will receive an API Key, which is required for API requests.
With your API Key ready, you can use CURL in PHP to make a request. Here's a working example:
<?php
// API request URL
$url = "https://api.lwl12.com/hitokoto/v1.php?type=social";
// Set request headers
$header = array(
"Content-Type: application/json;charset=UTF-8",
"API-Key: YOUR_API_KEY" // Replace with your actual API Key
);
// Create CURL object
$curl = curl_init();
// Set CURL options
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Execute request and get response
$response = curl_exec($curl);
// Close CURL connection
curl_close($curl);
// Decode JSON response
$data = json_decode($response, true);
// Check if request was successful
if ($data && isset($data['hitokoto'])) {
$randomSentence = $data['hitokoto'];
// Optional: Save $randomSentence to database
// Example for saving to MySQL
// $connection = mysqli_connect("localhost", "username", "password", "database");
// $randomSentence = mysqli_real_escape_string($connection, $randomSentence);
// mysqli_query($connection, "INSERT INTO sentences (sentence) VALUES ('$randomSentence')");
echo $randomSentence;
} else {
echo "Failed to retrieve random sentence";
}
?>
The code works as follows:
Ensure input sanitization when inserting into the database to prevent SQL injection.
In production environments, you should implement proper error handling for cases like API timeout or invalid keys. Additionally, avoid directly concatenating SQL strings—instead, use prepared statements for database operations.
With the instructions and sample code provided in this guide, you can quickly integrate the Baidu Wenxin Yiyan API into your PHP project and store the returned quotes in a database. This feature is useful for displaying quotes, daily messages, or creative content elements that enhance user engagement and interaction.