Home Backend Development PHP Tutorial PHP connects to Baidu Wenxin Yiyan API to obtain custom sorting and filtering methods for specific types of sentences

PHP connects to Baidu Wenxin Yiyan API to obtain custom sorting and filtering methods for specific types of sentences

Aug 27, 2023 pm 12:22 PM
api Oncidium Custom sorting filter method php connect to Baidu

PHP connects to Baidu Wenxin Yiyan API to obtain custom sorting and filtering methods for specific types of sentences

PHP connects to Baidu Wenxin Yiyan API to obtain custom sorting and filtering methods for specific types of sentences

When we need to display some sentences on a website or application, Baidu Wenxinyiyan API is a very good choice. It provides various types of sentences, such as inspirational, love, poetry, etc., which can bring different spiritual inspiration and emotional resonance to users. This article will introduce how to use PHP to connect to Baidu Wenxin Yiyan API and implement custom sorting and filtering methods.

First of all, we need to apply for the access key of Baidu Wenxin Yiyan API. Register and create a new application on the Baidu AI Open Platform website, and then obtain the API Key and Secret Key in the application.

Next, we can use PHP's curl library to connect to Baidu Wenxin Yiyan API and obtain sentence data. The following is a simple code example:

<?php
    $url = 'https://aip.baidubce.com/rpc/2.0/creation/v1/get_sentence';
    $api_key = 'YOUR_API_KEY';
    $secret_key = 'YOUR_SECRET_KEY';

    $type = 'love'; // 这里可以根据需要替换成其他类型的句子
    
    $params = [
        'type' => $type
    ];
    
    $headers = [
        'Content-Type: application/json',
        'charset: UTF-8'
    ];
    
    // 生成签名
    $timestamp = time();
    $signature = md5($api_key . $timestamp . $secret_key);
    
    $headers[] = 'X-Mock-Appid: 123456'; // 这里可以根据需要修改成自己的AppID
    $headers[] = 'X-Token: ' . $signature;
    $headers[] = 'X-Timestamp: ' . $timestamp;
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($ch);
    curl_close($ch);

    // 输出结果
    echo $result;
?>
Copy after login

In this sample code, we will use the love type sentence as an example. You can replace it with other types as needed, such as inspirational, sad, etc. At the same time, you also need to replace YOUR_API_KEY and YOUR_SECRET_KEY with the API Key and Secret Key you obtained on the Baidu AI open platform.

After executing the above code, you will get the returned JSON data, which contains multiple sentences. Now, let's implement custom sorting and filtering methods.

The first is the custom sorting method. Suppose we want to sort by the length of sentences, we can modify the code as follows:

// 输出结果
$result = json_decode($result, true);
$sentences = $result['sentences'];

// 自定义排序方法
function customSort($a, $b) {
    $aLength = mb_strlen($a['content'], 'utf-8');
    $bLength = mb_strlen($b['content'], 'utf-8');
    
    if ($aLength == $bLength) {
        return 0;
    }
    
    return ($aLength < $bLength) ? -1 : 1;
}

// 使用自定义排序方法进行排序
usort($sentences, 'customSort');

// 输出排序后的结果
foreach ($sentences as $sentence) {
    echo $sentence['content'] . "
";
}
Copy after login

In this example, the customSort function is a custom sorting method we defined to compare the lengths of two sentences. The usort function will use this custom sort method for sorting. Finally, we use a foreach loop to iterate through the sorted results and output them.

Next is the custom filtering method. Suppose we want to only display sentences with a length greater than 10, we can modify the code as follows:

// 输出结果
$result = json_decode($result, true);
$sentences = $result['sentences'];

// 自定义过滤方法
function customFilter($sentence) {
    $length = mb_strlen($sentence['content'], 'utf-8');
    
    return $length > 10;
}

// 使用自定义过滤方法进行过滤
$sentences = array_filter($sentences, 'customFilter');

// 输出过滤后的结果
foreach ($sentences as $sentence) {
    echo $sentence['content'] . "
";
}
Copy after login

In this example, the customFilter function is a custom filtering method we defined to determine whether the sentence length is greater than 10. The array_filter function will use this custom filtering method to filter. Finally, we use a foreach loop to iterate through the filtered results and output them.

To sum up, we connect to Baidu Wenxin Yiyan API to obtain specific types of sentences, and implement custom sorting and filtering functions. By modifying the parameters in the code, you can flexibly obtain different types of sentences and sort and filter them according to your needs. I hope this article has provided some help for everyone in using Baidu Wenxinyiyan API in PHP development.

The above is the detailed content of PHP connects to Baidu Wenxin Yiyan API to obtain custom sorting and filtering methods for specific types of sentences. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1253
29
C# Tutorial
1227
24
How to crawl and process data by calling API interface in PHP project? How to crawl and process data by calling API interface in PHP project? Sep 05, 2023 am 08:41 AM

How to crawl and process data by calling API interface in PHP project? 1. Introduction In PHP projects, we often need to crawl data from other websites and process these data. Many websites provide API interfaces, and we can obtain data by calling these interfaces. This article will introduce how to use PHP to call the API interface to crawl and process data. 2. Obtain the URL and parameters of the API interface. Before starting, we need to obtain the URL of the target API interface and the required parameters.

Oracle API Usage Guide: Exploring Data Interface Technology Oracle API Usage Guide: Exploring Data Interface Technology Mar 07, 2024 am 11:12 AM

Oracle is a world-renowned database management system provider, and its API (Application Programming Interface) is a powerful tool that helps developers easily interact and integrate with Oracle databases. In this article, we will delve into the Oracle API usage guide, show readers how to utilize data interface technology during the development process, and provide specific code examples. 1.Oracle

React API Call Guide: How to interact and transfer data with the backend API React API Call Guide: How to interact and transfer data with the backend API Sep 26, 2023 am 10:19 AM

ReactAPI Call Guide: How to interact with and transfer data to the backend API Overview: In modern web development, interacting with and transferring data to the backend API is a common need. React, as a popular front-end framework, provides some powerful tools and features to simplify this process. This article will introduce how to use React to call the backend API, including basic GET and POST requests, and provide specific code examples. Install the required dependencies: First, make sure Axi is installed in the project

How to deal with Laravel API error problems How to deal with Laravel API error problems Mar 06, 2024 pm 05:18 PM

Title: How to deal with Laravel API error problems, specific code examples are needed. When developing Laravel, API errors are often encountered. These errors may come from various reasons such as program code logic errors, database query problems, or external API request failures. How to handle these error reports is a key issue. This article will use specific code examples to demonstrate how to effectively handle Laravel API error reports. 1. Error handling in Laravel

Oracle API integration strategy analysis: achieving seamless communication between systems Oracle API integration strategy analysis: achieving seamless communication between systems Mar 07, 2024 pm 10:09 PM

OracleAPI integration strategy analysis: To achieve seamless communication between systems, specific code examples are required. In today's digital era, internal enterprise systems need to communicate with each other and share data, and OracleAPI is one of the important tools to help achieve seamless communication between systems. This article will start with the basic concepts and principles of OracleAPI, explore API integration strategies, and finally give specific code examples to help readers better understand and apply OracleAPI. 1. Basic Oracle API

Development suggestions: How to use the ThinkPHP framework for API development Development suggestions: How to use the ThinkPHP framework for API development Nov 22, 2023 pm 05:18 PM

Development suggestions: How to use the ThinkPHP framework for API development. With the continuous development of the Internet, the importance of API (Application Programming Interface) has become increasingly prominent. API is a bridge for communication between different applications. It can realize data sharing, function calling and other operations, and provides developers with a relatively simple and fast development method. As an excellent PHP development framework, the ThinkPHP framework is efficient, scalable and easy to use.

Custom sorting: Implementation method of sorting using JS array sort() method Custom sorting: Implementation method of sorting using JS array sort() method Dec 28, 2023 am 10:59 AM

How to use JS array sorting: sort() method for custom sorting In JavaScript, arrays are a very common and important data type. When we need to sort the elements in an array, we can use the sort() method of the array. The sort() method sorts the array elements according to the default sorting rules, but sometimes we may need to customize the sorting of the array according to our own needs. This article will introduce in detail how to use the sort() method for custom sorting, and provide specific

Save API data to CSV format using Python Save API data to CSV format using Python Aug 31, 2023 pm 09:09 PM

In the world of data-driven applications and analytics, APIs (Application Programming Interfaces) play a vital role in retrieving data from various sources. When working with API data, you often need to store the data in a format that is easy to access and manipulate. One such format is CSV (Comma Separated Values), which allows tabular data to be organized and stored efficiently. This article will explore the process of saving API data to CSV format using the powerful programming language Python. By following the steps outlined in this guide, we will learn how to retrieve data from the API, extract relevant information, and store it in a CSV file for further analysis and processing. Let’s dive into the world of API data processing with Python and unlock the potential of the CSV format

See all articles