In web development, we often need to incorporate random phrases or quotes to add interest and engagement to the page. The Baidu Wenxin Yi Yan API provides a convenient way to retrieve random phrases and apply them to webpages. This article will guide you through how to use PHP to connect with the Baidu Wenxin Yi Yan API and generate web excerpts from the API responses.
Before connecting to the Baidu Wenxin Yi Yan API, make sure that PHP is installed on your server and the server can access the internet.
<?php // Set the request URL and parameters for the Wenxin Yi Yan API $url = "http://api.vikingship.xyz/wisdom/api/one"; $params = [ 'secret_key' => 'your_secret_key', // Replace with the access key you obtained ]; // Initialize a cURL session $curl = curl_init(); // Set cURL options for the request curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params)); // Execute the cURL request and get the response data $response = curl_exec($curl); curl_close($curl); // Decode the returned JSON data $data = json_decode($response, true); // Extract the excerpt content from the response $excerpt = $data['excerpts']; // Output the excerpt content echo $excerpt; ?>
In the code above, the request URL and parameters for the Wenxin Yi Yan API are set. You will need to replace 'your_secret_key' with the access key you received. The cURL library is used to make an HTTP request, and the response is fetched using curl_exec(). Finally, the JSON response is decoded using json_decode() and the excerpt content is extracted and displayed.
Once you apply the code above to your webpage, you can generate web excerpts. Here’s a simple example:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Web Excerpt Generator</title> </head> <body> <h1>Web Excerpt</h1> <p><?php include 'get_excerpt.php'; ?></p> </body> </html>
In the example above, we include the PHP code for retrieving the excerpt by using <?php include 'get_excerpt.php'; ?> and display the excerpt within the
tag on the webpage.
By connecting to the Baidu Wenxin Yi Yan API and retrieving random phrases, we can easily apply them to a webpage for generating excerpts. Using PHP to handle the API request and response parsing makes the process simple and efficient. This method can add interest and engagement to a website, improving the overall user experience.
Related Tags:
API