Hitokoto (一言) is an open sentence API that provides quotes from various categories like animation, comics, and novels. In this article, we will explain how to use PHP to connect to the Baidu Wenxin Hitokoto API to fetch and display daily quotes.
First, register an account on Baidu Cloud. Then, create a new application in the console and obtain the corresponding API key.
Create a PHP file in your project folder and name it "hitokoto.php".
In the "hitokoto.php" file, write the following PHP code:
<?php $apikey = "YOUR_API_KEY"; $url = "https://aip.baidubce.com/rpc/2.0/aq/suggest"; $data = array( 'word' => '一', 'count' => 10, ); // Convert data to JSON format $data_string = json_encode($data); // Set request headers $headers = array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string), 'apikey: ' . $apikey, ); // Initialize CURL $ch = curl_init(); // Set CURL options curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // Send request and get response $response = curl_exec($ch); // Close CURL curl_close($ch); // Parse response data $data = json_decode($response, true); // Extract hitokoto content if(isset($data['result']) && !empty($data['result'])){ $hitokoto = $data['result'][0]['hitokoto']; echo $hitokoto; } else { echo "Unable to fetch hitokoto content"; } ?>
Replace "YOUR_API_KEY" in the code with the API key you obtained. The code uses cURL to send an HTTP request to the Baidu Wenxin Hitokoto API, receives JSON response data, parses it, and displays the daily quote on your page.
Save and upload the "hitokoto.php" file to your website server. Visiting this file in a browser will display the daily quote.
Using PHP to connect to the Baidu Wenxin Hitokoto API makes it easy to fetch daily quotes and display them on your website. This article provides complete code examples to quickly get started. You can modify and extend the code according to your needs for different scenarios.
Related Tags:
API