Baidu Wenxin Yiyan offers an API that provides daily quotes, allowing developers to easily fetch inspirational phrases. PHP, as a widely-used server-side language, can easily connect to this API to obtain data. This article explains how to use PHP with cURL to call the Baidu Wenxin Yiyan API and parse the returned JSON data.
The example demonstrates setting the temperature parameter to 0.6 to retrieve a high-quality daily quote.
Before writing code, you need to complete the following preparations:
Visit the Baidu Cloud official website, register and log in, create an application selecting Baidu Wenxin Yiyan service, then generate and save the API key for use.
PHP uses the cURL extension to make HTTP requests. Make sure your server environment has cURL installed. Example installation on Linux:
sudo apt-get install php-curl
or
sudo yum install php-curl
After installation, restart your PHP service to enable the extension.
The following PHP code demonstrates how to send a request to Baidu Wenxin Yiyan API using cURL and retrieve the daily quote:
// Baidu Wenxin Yiyan API URL
$url = 'https://v1.hitokoto.cn/?c=a&encode=json';
// Insert your API key
$api_key = 'YOUR_API_KEY';
// Initialize cURL session
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('apikey:' . $api_key));
// Execute request and get response
$response = curl_exec($ch);
// Close cURL session
curl_close($ch);
// Decode JSON data
$data = json_decode($response, true);
// Output the daily quote
echo $data['hitokoto'];
The code sets the request URL and includes the API key in the HTTP headers to ensure authentication. It then parses the JSON response and outputs the "hitokoto" field, which is the daily quote.
This article introduced how to use PHP with cURL to connect to Baidu Wenxin Yiyan API and fetch the daily quote, covering API key registration, environment setup, and sample code. By calling this API, developers can easily integrate beautiful quotes into websites or applications, enhancing user experience.
With PHP’s flexibility, you can adjust API parameters as needed to create more practical features.