Baidu Wenxin Yiyan provides an API for random sentences, suitable for displaying warm, motivational, or philosophical content. This article demonstrates how to use PHP to call this API and analyze the retrieved data, helping developers utilize the API more efficiently.
First, you need to get the API endpoint for Baidu Wenxin Yiyan, which can be found in the official documentation on Baidu Developer Platform.
The following example demonstrates how to call the API and retrieve a sentence:
<?php // Set the API endpoint $api_url = "http://xxxxxxx"; // Send request and get response $response = file_get_contents($api_url); // Parse the returned JSON data $data = json_decode($response, true); // Extract sentence content $sentence = $data['sentence']; // Print the sentence echo "Wenxin Yiyan: ".$sentence; ?>
This code performs a simple API call and outputs the retrieved sentence.
We can count the number of sentences retrieved by the API, for example, by incrementing a variable each time a request succeeds:
<?php // Initialize statistics variable $count = 0; // Loop to call the API for($i=0; $i<10; $i++){ $response = file_get_contents($api_url); $data = json_decode($response, true); $count++; } // Print the total count echo "Total sentences retrieved: ".$count; ?>
This example calls the API ten times and counts the total number of sentences retrieved.
Based on the statistics, we can perform simple analysis, such as finding the longest and shortest sentences:
<?php // Initialize variables $count = 0; $longest_sentence = ""; $shortest_sentence = ""; // Loop to call the API for($i=0; $i<10; $i++){ $response = file_get_contents($api_url); $data = json_decode($response, true); $count++; // Get sentence content $sentence = $data['sentence']; // Check for longest sentence if(strlen($sentence) > strlen($longest_sentence)){ $longest_sentence = $sentence; } // Check for shortest sentence if(strlen($sentence) < strlen($shortest_sentence) || $shortest_sentence == ""){ $shortest_sentence = $sentence; } } // Print statistics results echo "Total sentences retrieved: ".$count; echo "Longest sentence: ".$longest_sentence; echo "Shortest sentence: ".$shortest_sentence; ?>
This code updates the longest and shortest sentences during each API call and outputs the final statistics.
By using PHP to call the Baidu Wenxin Yiyan API and performing data statistics and analysis, developers can easily retrieve interesting sentences and process them further. This enhances the practical value of the API and provides convenience for future data analysis and display.