When developing a website, using open APIs to fetch data is a common requirement. Baidu Wenxin Hitokoto API is a very popular interface that returns various types of elegant sentences. In this article, we will explore how to use PHP to connect to the Baidu Wenxin Hitokoto API and retrieve specific types of sentences, along with various filtering methods to meet our needs.
Baidu Wenxin Hitokoto API is a free public API that provides various types of famous quotes, inspirational quotes, anime lines, and more, making it perfect for creating quote-based websites. You can get the API address from its official website.
This API requires no authentication and can return data simply by sending an HTTP request. Here's how to send a GET request using PHP's file_get_contents
In the above code, we added the
The result is a PHP array containing information such as the quote, author, and source. You can retrieve specific content as follows:
To fetch specific types of sentences, we can add different parameters to the request URL. For example, to get "programming" type sentences in Chinese text format, use the following request:
In this request, we use the c=program parameter to get "programming" type sentences, and specify that the response should be in text format with the UTF-8 character set.
To avoid inappropriate content on your website, we can filter out sensitive words using regular expressions in PHP. The following code demonstrates how to replace profanities using the preg_replace function:
Using regular expressions, we replace the sensitive words with "**", thus effectively cleaning the sentence of profanities.
To ensure the layout remains tidy and visually appealing, we can limit the length of sentences. The following code demonstrates how to truncate a sentence to no more than 20 characters:
We use the mb_substr function to truncate the sentence, limiting it to a maximum of 20 characters.
To ensure that users' inputs are safe, we need to remove HTML tags from the sentence. The following method uses the strip_tags function to filter HTML tags:
By using the strip_tags function, we obtain the sentence with all HTML tags removed, leaving only plain text content.
In this article, we have learned how to use PHP to connect to the Baidu Wenxin Hitokoto API and retrieve specific types of sentences. We also discussed various filtering methods, including filtering sensitive words, limiting sentence length, and removing HTML tags. By setting parameters in the API request, combined with techniques like regular expressions, length restrictions, and tag filtering, we can retrieve and process sentences to fit our needs. You can further extend these methods based on your specific requirements for better user experience on your website.