Current Location: Home> Latest Articles> How to Implement Baidu Wenxin Yiyan Random Sentence Sorting Feature in PHP

How to Implement Baidu Wenxin Yiyan Random Sentence Sorting Feature in PHP

M66 2025-07-02

Introduction

Random sentence sorting is a common requirement in website development. Baidu Wenxin Yiyan provides an easy-to-use API, allowing developers to retrieve random sentences and sort them. This article will guide you through the steps to implement this functionality using PHP.

Obtain API Key

First, you need to visit the official Baidu Wenxin Yiyan website, register an account, and obtain your API key. Make sure to save your key for use in your code.

Implementing the Random Sentence Sorting Feature

Below is an example of how to call the Baidu Wenxin Yiyan API in PHP and implement the random sentence sorting feature:

<?php<br>// Set the API key<br>$apiKey = "your_api_key";<br><br>// API request URL<br>$url = "https://api.lwl12.com/hitokoto/";<br><br>// Send the request and get the data<br>$response = file_get_contents($url . "?encode=json");<br><br>// Decode the JSON data into a PHP array<br>$data = json_decode($response, true);<br><br>// Sort the sentences<br>usort($data, function($a, $b) {<br>    return strcmp($a['hitokoto'], $b['hitokoto']);<br>});<br><br>// Output the result<br>foreach ($data as $item) {<br>    echo $item['hitokoto'] . "<br/>";<br>}<br>?>

Code Explanation

In the above code, we first set the API key and send an HTTP request using the file_get_contents() function to retrieve the response. Next, we decode the returned JSON data into a PHP array. We then use the usort() function to sort the data based on the dictionary order of the sentences. Finally, we use a foreach loop to output the sorted sentences.

Important Notes

This sample code is a simple implementation. In real-world applications, it's recommended to add error handling and exception catching to improve the stability and reliability of the code.

Conclusion

With the tutorial in this article, you can easily implement the sorting of random sentences retrieved via the Baidu Wenxin Yiyan API using PHP. We hope this article helps you address related challenges in your development process.