Baidu Wenxin Yiyan is an API that provides random motivational, philosophical, poetic, and other quotes, aiming to bring positive energy and inspiration to users. In this article, we will implement the Baidu Wenxin Yiyan API using PHP, showing a detailed code example to help developers quickly integrate this functionality.
By following these steps, you can successfully implement the Baidu Wenxin Yiyan API in your PHP project:
First, you need to visit the Baidu Developer Platform and register for a developer account. After registration, log in to your account, create a new application, and obtain the appid and appkey for the application.
Create a function called apiRequest that accepts a URL as a parameter and sends a request to the specified URL to retrieve the response data.
function apiRequest($url) { $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true )); $response = curl_exec($curl); curl_close($curl); return $response; }
Create a function called getOneWord that does not accept any parameters. This function will call the apiRequest function to fetch a random quote from the API, then return the result in JSON format.
function getOneWord() { $url = 'http://api.lwl12.com/hitokoto/main/get'; $response = apiRequest($url); $result = json_decode($response); return $result->hitokoto; }
In the area where you want to display the quote, simply call the getOneWord function to retrieve and show the quote content.
$oneWord = getOneWord(); echo $oneWord;
By following these steps, you can easily implement the Baidu Wenxin Yiyan API on your website or application. By calling this API, you can display random motivational, philosophical, poetic quotes, offering users positive energy. We hope this article provides valuable help to you.