Home  >  Article  >  Backend Development  >  How to use PHP code to call Baidu Wenxin Yiyan interface?

How to use PHP code to call Baidu Wenxin Yiyan interface?

王林
王林Original
2023-08-12 10:28:421247browse

How to use PHP code to call Baidu Wenxin Yiyan interface?

How to use PHP code to call Baidu Wenxin Yiyan interface?

Baidu Wenxin Yiyan interface is an API that provides random sentences, which can be used on the homepage of the website, at the end of the article, etc., to add a literary atmosphere. This article will introduce in detail how to use PHP code to call Baidu Wenxin Yiyan interface.

First, we need to obtain the URL of Baidu Wenxin Yiyan interface. Open the official website of Baidu Wenxin Yiyan (https://developer.baidu.com/quote) in the browser and find the API URL on the page, as shown below:

https://developer.baidu.com/quote/v1/api/quote

Next, we pass PHP's file_get_contents() function to get the random sentences returned by the API. Pass the API URL as a parameter to the function and save the returned JSON format data.

$url = 'https://developer.baidu.com/quote/v1/api/quote';
$data = file_get_contents($url);

Then, we need to parse the returned JSON format data into a PHP array in order to obtain the required sentence content.

$result = json_decode($data, true);

Now, we can get the content and author of the random sentences. In the parsed array, the content is stored under the quote key and the author is stored under the author key.

$quote = $result['quote'];
$author = $result['author'];

Finally, we can display the obtained random sentences on the web page. Use HTML tags and PHP code to format the content and author and output it to the page.

echo '<p>' . $quote . '</p>';
echo '<p>' . '——' . $author . '</p>';

Integrate the above PHP code into a PHP file to call Baidu Wenxin Yiyan interface on the web page and display random sentences.

Through the above steps, we successfully used PHP code to call Baidu Wenxin Yiyan interface and display random sentences on the web page. You can embed this code into your website project according to your own needs, and adjust the style and position as needed.

I hope this article can help you and make your website more artistic and interesting!

The above is the detailed content of How to use PHP code to call Baidu Wenxin Yiyan interface?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn