Current Location: Home> Latest Articles> How to Use PHP to Implement the Baidu Wenxin Yiyan API and Retrieve Famous Quotes

How to Use PHP to Implement the Baidu Wenxin Yiyan API and Retrieve Famous Quotes

gitbox 2025-06-16

1. Introduction

In modern web development, enriching the content of a website is crucial for enhancing the user experience. By calling third-party APIs, websites can access real-time data, enrich content, and increase user engagement. Baidu Wenxin Yiyan provides an API that can randomly return famous quotes or classic poetry, making it ideal for use in the introduction or overview sections of a website. In this article, we will use PHP to implement this API, retrieve interesting quotes, and display them on the site.

2. Related API

2.1 Baidu Wenxin Yiyan API

The Baidu Wenxin Yiyan API offers a service that randomly returns famous quotes or classic poetry. The API endpoint is https://api.imjad.cn/. By accessing this URL, users can obtain a random quote.

2.2 Using GET Request to Fetch Data

In PHP, we can use a GET request to call this API and retrieve the data. The request can be made using file_get_contents

3. Implementing Baidu Wenxin Yiyan API

Next, we will demonstrate how to implement the Baidu Wenxin Yiyan API in PHP. By parsing the returned data, we can extract the quote, author, source, and related links.


/**
 * Fetch Baidu Wenxin Yiyan API data
 */
function hitokoto() {
    $url = "https://api.imjad.cn/hitokoto/?encode=json";
    $data = json_decode(file_get_contents($url));
    $text = $data->hitokoto;
    $author = $data->from;
    $source = $data->from_who;
    $url = $data->url;
    return array('text' => $text, 'author' => $author, 'source' => $source, 'url' => $url);
}

The code above fetches data from the API and parses the quote, author, source, and related URL. The extracted information is returned as an array for easy use later.

4. Implementation Result

Once implemented, the retrieved famous quotes can be displayed in a simple manner on your website, adding depth and interest to the content. This feature is highly suitable for blogs, Q&A websites, or any site that requires dynamic content updates.

5. Conclusion

This article showed how to implement the Baidu Wenxin Yiyan API using PHP. By sending simple GET requests, we can retrieve random famous quotes and parse the returned data to display on the website. Through this case study, we have learned how to send GET requests in PHP and handle the returned data, greatly enhancing the dynamic nature of website content and improving user experience.