Current Location: Home> Latest Articles> PHP Integration with Baidu Wenxin Yiyan API: Fetch Random Sentences and Generate Poems

PHP Integration with Baidu Wenxin Yiyan API: Fetch Random Sentences and Generate Poems

M66 2025-07-29

Overview

With the rapid advancement of artificial intelligence technologies, especially in natural language processing, developers can fetch interesting data via APIs. The Baidu Wenxin Yiyan API is a great example, as it provides random sentences and generates poems. This article introduces how to use PHP to connect to the Baidu Wenxin Yiyan API, fetch random sentences, and generate poems from them.

Preparation

Before getting started, you need to complete the following preparations:

  • Register for a Baidu Developer account and obtain your API Key and Secret Key.
  • Create a PHP file (e.g., poem_generator.php).

Writing PHP Code

Next, we'll write the PHP code to connect to the Baidu Wenxin Yiyan API and generate a poem.

PHP Code Example

<?php
// Define API Key and Secret Key
define('API_KEY', 'your_api_key');
define('SECRET_KEY', 'your_secret_key');
// Define the API request URL
define('API_URL', 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/text_cls/poem');
// Define HTTP request headers
$headers = array(
    'Content-Type: application/json;charset=UTF-8',
);
// Construct API request data
$data = array(
    'model_id' => 'your_model_id',
    'text' => '',
);
// Fetch random sentence
function getRandomSentence() {
    $curl = curl_init();
    $timeout = 30;
    $url = "https://v1.hitokoto.cn/";
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
    $result = curl_exec($curl);
    curl_close($curl);
    $data = json_decode($result, true);
    if (isset($data['hitokoto'])) {
        return $data['hitokoto'];
    }
    return "";
}
// Generate poem
function generatePoem() {
    $sentence = getRandomSentence();
    $data['text'] = $sentence;
    $ch = curl_init(API_URL);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    $response = curl_exec($ch);
    curl_close($ch);
    $result = json_decode($response, true);
    if (isset($result['results']) && count($result['result']) > 0) {
        $poem = $result['result'][0]['poem'];
        echo $poem;
    } else {
        echo "Failed to generate poem";
    }
}
// Call the function to generate a poem
generatePoem();
?>

Code Explanation

In the above code, replace `your_api_key` and `your_secret_key` with your own API Key and Secret Key, and replace `your_model_id` with your created model ID.

The code works by first fetching a random sentence using the `getRandomSentence()` function, then passing that sentence to the API in the `generatePoem()` function. The API responds with a poem, which is then displayed.

Deployment and Running

Save the above code as `poem_generator.php`, upload it to a PHP-supported server, and simply access it via your browser to generate a random poem.

Conclusion

This article has shown you how to connect to the Baidu Wenxin Yiyan API using PHP, fetch random sentences, and generate poems. This technology can be applied not only for poetry creation but also for other natural language processing tasks, offering more creativity and fun in your projects.

  • Related Tags:

    API