Current Location: Home> Latest Articles> PHP Tutorial: How to Call Baidu Wenxin Yiyan API and Format Returned Data

PHP Tutorial: How to Call Baidu Wenxin Yiyan API and Format Returned Data

gitbox 2025-08-04

Introduction

Baidu Wenxin Yiyan offers an open API that returns a variety of random sentences, including humorous, inspirational, and philosophical content. This article demonstrates how to use PHP to fetch data from this API and format it for easier display and use.

Preparation

Get the API Endpoint

First, confirm the API URL address. Here is an example:

<span class="fun">$url = 'https://v1.hitokoto.cn';</span>

Fetch JSON Data from the API

Use PHP's file_get_contents() function to read the API response, then convert the JSON data into a PHP array with json_decode(). Example code:

$data = file_get_contents($url);
$data = json_decode($data, true);

This way, you obtain an associative array containing the API data, ready for further processing.

Data Formatting and Conversion

Format Sentence Content

To prevent any HTML tags in the API response from affecting page display, use htmlspecialchars() to escape the sentence content:

<span class="fun">$content = htmlspecialchars($data['hitokoto']);</span>

Format Sentence Source

The source of the sentence may also contain special characters and should be escaped similarly:

<span class="fun">$source = htmlspecialchars($data['from']);</span>

Handle Author Information

Some sentences include author info. Use isset() to check if the author field exists, then format it accordingly:

$author = '';
if (isset($data['creator'])) {
    $author = htmlspecialchars($data['creator']);
}

Display the Final Result

After formatting, you can output the content, source, and author information as follows:

echo $content;
echo $source;
echo $author;

You can place these outputs anywhere on your webpage or integrate them into other business logic as needed.

Summary

This article showed how to retrieve and process random sentences from the Baidu Wenxin Yiyan API using PHP. We used file_get_contents() to fetch JSON data, json_decode() to convert it into an array, and htmlspecialchars() to escape the content, source, and author fields, avoiding display issues caused by HTML tags. This straightforward approach makes it easy to use and display API data in your projects.