Current Location: Home> Latest Articles> Using PHP to Connect to Baidu Wenxin Yiyan API for Sentence Data Retrieval, Sorting, and Pagination

Using PHP to Connect to Baidu Wenxin Yiyan API for Sentence Data Retrieval, Sorting, and Pagination

M66 2025-10-15

Using PHP to Connect to Baidu Wenxin Yiyan API for Sentence Data Retrieval, Sorting, and Pagination

As web applications continue to evolve, more developers rely on APIs to dynamically fetch various types of content. The Baidu Wenxin Yiyan API provides access to a wide range of sentence data, allowing developers to retrieve and display them based on specific needs. This guide demonstrates how to connect to the API with PHP, process the returned data, and implement sorting and pagination features for smooth web display.

Register a Baidu Developer Account and Create an Application

Before using the Wenxin Yiyan API, you must register a Baidu Developer account and create an application in the Baidu AI Cloud console. Once created, you will receive an API Key and Secret Key — these are essential for authentication in later API requests.

Connecting to the API and Sending Requests with PHP

In PHP, the cURL library can be used to send HTTP requests and handle responses. The example below shows how to set up the API request, send data, and process the returned JSON response:

<?php
$url = 'http://api.xxxxxx.com/xxx/xxx'; // Replace with your actual API endpoint
$apikey = 'xxxxxxxxxxxxx'; // Replace with your actual API Key

$data = array(
    'type' => 'type_parameter', // Example: famous
    'num' => 'number_of_items', // Example: 10
);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'apikey:'.$apikey));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

$response = curl_exec($ch);
curl_close($ch);

$result = json_decode($response, true);
if ($result && $result['status'] == 0) {
    $sentences = $result['result'];
    // Process returned sentence data
} else {
    echo 'Request failed';
}
?>

In the example above, replace the URL and API key with your own. The type parameter determines which sentence category to retrieve, while num specifies how many sentences to fetch in a single request.

Sorting the Data

Once the sentence data is stored in an array, you can use PHP’s usort() function to sort it based on specific criteria. The following example sorts the data in ascending order by ID:

<?php
// Sort sentence data in ascending order by ID
usort($sentences, function($a, $b) {
    return $a['id'] - $b['id'];
});
?>

This method allows for flexible data ordering, such as sorting by date, ID, or other custom fields depending on your display requirements.

Implementing Pagination

For better user experience and performance, it’s recommended to implement pagination when displaying data on the front end. You can easily achieve this using PHP’s array_slice() function. Here’s an example:

<?php
$page = isset($_GET['page']) ? $_GET['page'] : 1; // Current page
$pageSize = 10; // Number of items per page

$start = ($page - 1) * $pageSize; // Calculate starting position
$result = array_slice($sentences, $start, $pageSize); // Get current page data

// Display the sentence data
foreach ($result as $sentence) {
    echo $sentence['content'] . '<br>';
}

// Generate pagination links
$totalPage = ceil(count($sentences) / $pageSize);
for ($i = 1; $i <= $totalPage; $i++) {
    $active = $i == $page ? 'active' : '';
    echo "<a href='?page={$i}' class='{$active}'>{$i}</a> ";
}
?>

This pagination example retrieves the current page number, calculates the offset, slices the array, and then outputs pagination links for easy navigation between pages.

Conclusion

In this article, you learned how to use PHP to connect to Baidu’s Wenxin Yiyan API, retrieve specific types of sentence data, and implement sorting and pagination. This approach is particularly useful for developers building dynamic content-driven websites or intelligent applications that require real-time data retrieval and display.