


How to connect Baidu Wenxin Yiyan API with PHP to obtain random sentences and generate poems
How to connect PHP to Baidu Wenxin Yiyan API to obtain random sentences and generate poems
With the rapid development of artificial intelligence technology and the improvement of natural language processing capabilities, We can use APIs to obtain some interesting data, such as Baidu Wenxin Yiyan API. This article introduces how to use PHP to connect to Baidu Wenxin Yiyan API to obtain random sentences, and display these sentences in the form of poetry.
First of all, we need to prepare:
- Register a Baidu developer account and obtain the API Key and Secret Key. For specific operation methods, please refer to the documentation on the Baidu Developer official website.
- Create a PHP file named
poem_generator.php
.
Next, let us write PHP code to realize the function of connecting to Baidu Wenxin Yiyan API and generating poetry.
<?php // 定义API Key和Secret Key define('API_KEY', 'your_api_key'); define('SECRET_KEY', 'your_secret_key'); // 定义API请求地址 define('API_URL', 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/text_cls/poem'); // 定义HTTP请求头 $headers = array( 'Content-Type: application/json;charset=UTF-8', ); // 构造API请求数据 $data = array( 'model_id' => 'your_model_id', 'text' => '', ); // 获取随机语句 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); // 解析返回的JSON数据 $data = json_decode($result, true); if(isset($data['hitokoto'])){ return $data['hitokoto']; } return ""; } // 生成诗歌 function generatePoem() { $sentence = getRandomSentence(); // 获取随机语句 $data['text'] = $sentence; // 发送API请求 $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); // 解析API返回的结果 $result = json_decode($response, true); if(isset($result['results']) && count($result['result']) > 0) { $poem = $result['result'][0]['poem']; // 获取诗歌内容 echo $poem; } else { echo "生成诗歌失败"; } } // 调用生成诗歌函数 generatePoem(); ?>
In the above code, your_api_key
and your_secret_key
need to be replaced with your own API Key and Secret Key. At the same time, your_model_id
also needs to be replaced with the model ID you created yourself.
In the code, we first define the API request address, request headers, and request data, and use the getRandomSentence()
function to obtain random sentences. We then use the generatePoem()
function to generate poetry from the results returned by the API request.
Save the above code as a poem_generator.php
file and upload it to a server that supports PHP. Random poems can be generated by accessing the file.
Summary:
This article introduces the method of using PHP to connect to Baidu Wenxin Yiyan API to obtain random sentences and generate poems from these sentences. By calling the API interface, we can obtain interesting data and apply it to applications such as poetry generation, bringing more fun and creativity to our programs. Hope this article is helpful to you.
The above is the detailed content of How to connect Baidu Wenxin Yiyan API with PHP to obtain random sentences and generate poems. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.
