Home > Article > Backend Development > Implementation steps for connecting Baidu Wenxin Yiyan API with PHP to obtain a daily sentence
PHP steps to connect Baidu Wenxin Yiyan API to obtain daily sentences
Yiyan (hitokoto) is an open sentence interface that can obtain various types sentences, such as animations, comics, novels, etc. In this article, we will introduce how to use PHP to connect to Baidu Wenxin Yiyan API to obtain and display a daily sentence.
Step 1: Apply for API key
First, we need to go to Baidu Open Cloud (https://cloud.baidu.com/) website to register an account. Then, create a new application in the console and obtain an API key.
Step 2: Create PHP file
In your project folder, create a new PHP file and name it "hitokoto.php".
Step 3: Write PHP code
Write the following PHP code in the "hitokoto.php" file:
<?php $apikey = "YOUR_API_KEY"; $url = "https://aip.baidubce.com/rpc/2.0/aq/suggest"; $data = array( 'word' => '一', 'count' => 10, ); // 将数据转换为JSON格式 $data_string = json_encode($data); // 设置请求头 $headers = array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string), 'apikey: ' . $apikey, ); // 初始化CURL $ch = curl_init(); // 设置CURL选项 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); // 发送请求并获取响应 $response = curl_exec($ch); // 关闭CURL curl_close($ch); // 处理响应数据 $data = json_decode($response, true); // 提取一言内容 if(isset($data['result']) && !empty($data['result'])){ $hitokoto = $data['result'][0]['hitokoto']; echo $hitokoto; } else { echo "无法获取一言内容"; } ?>
In the code, replace "YOUR_API_KEY" with the API you applied for key.
In this code, we use the cURL library to send HTTP requests to Baidu Wenxin Yiyan API and obtain the JSON data returned by the API. We then parse the JSON data, extract a chunk of it, and display it on the page.
Step 4: Test the code
Save and upload the "hitokoto.php" file to your website server. Then, access the file in your browser and you should see the sentence of the day displayed.
Summary
By using PHP to connect to Baidu Wenxin Yiyan API, we can easily obtain the content of the daily sentence and display it on our website. This tutorial provides code examples so you can quickly get started using the API. You can modify and customize the code according to your own needs to adapt to different application scenarios.
The above is the detailed content of Implementation steps for connecting Baidu Wenxin Yiyan API with PHP to obtain a daily sentence. For more information, please follow other related articles on the PHP Chinese website!