Home Backend Development PHP Tutorial How to implement PHP connection to Baidu Wenxin Yiyan API to obtain random statements and display them in pages

How to implement PHP connection to Baidu Wenxin Yiyan API to obtain random statements and display them in pages

Aug 25, 2023 pm 09:36 PM
Pass the appropriate parameters

How to implement PHP connection to Baidu Wenxin Yiyan API to obtain random statements and display them in pages

How PHP connects to Baidu Wenxin Yiyan API to obtain random statements and display them in pages

  1. Introduction
    Baidu Wenxin Yiyan is a Provides an API interface for random statements. We can use PHP to connect to the API, obtain random statements, and then display them in pages. This article will introduce how to use PHP to connect to Baidu Wenxin Yiyan API, and combine it with code examples to achieve paging display of random statements.
  2. Get API key
    First, we need to register a developer account on Baidu Wenxinyiyan’s official website and obtain the API key. After the registration is completed, log in to the account, find the API key in the personal center, and copy the key for subsequent use.
  3. Connect API
    We use PHP's curl function to connect to Baidu Wenxin Yiyan API. The following is a code example for connecting to the API:
<?php
$api_url = 'https://api.bingstudio.cn/wenxin/yiyan';
$api_key = 'your_api_key'; // 替换成你的API密钥

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => $api_url,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'X-Api-Key: ' . $api_key
  )
));

$response = curl_exec($curl);
$error = curl_error($curl);

curl_close($curl);

if ($error) {
  echo 'API连接错误: ' . $error;
  exit;
}

$data = json_decode($response, true);

if ($data['code'] !== 0) {
  echo 'API返回错误: ' . $data['msg'];
  exit;
}

$quote = $data['data']['content'];
$author = $data['data']['author'];

echo '随机语句:' . $quote;
echo '作者:' . $author;
?>
Copy after login
  1. Page display
    Next, we need to implement the function of displaying random statements in pages. We can use PHP's paging class to handle paging logic. The following is a code example:
<?php
class Pager {
    private $total;            // 总记录数
    private $pageSize;         // 每页显示的记录数
    private $pageNum;          // 当前页码
    private $totalPages;       // 总页数
    private $start;            // 当前页在数据库中的起始位置
    private $conn;             // 数据库连接对象

    // 构造方法,初始化分页类对象
    function __construct($total, $pageSize, $conn) {
        $this->total = $total;
        $this->pageSize = $pageSize;
        $this->totalPages = ceil($this->total / $this->pageSize);
        $this->conn = $conn;
        $this->getPageNum();
        $this->getStart();
    }

    // 获取当前页码
    function getPageNum() {
        $pageParam = isset($_GET['page']) ? intval($_GET['page']) : 1;
        if ($pageParam < 1) {
            $this->pageNum = 1;
        } elseif ($pageParam > $this->totalPages) {
            $this->pageNum = $this->totalPages;
        } else {
            $this->pageNum = $pageParam;
        }
    }

    // 获取当前页的起始位置
    function getStart() {
        $this->start = ($this->pageNum - 1) * $this->pageSize;
    }

    // 获取分页数据
    function getPagerData($sql) {
        $sql = $sql . " LIMIT $this->start, $this->pageSize";
        $result = $this->conn->query($sql);
        return $result;
    }

    // 生成分页链接
    function generateLinks($url) {
        $links = '';
        if ($this->pageNum > 1) {
            $prev = $this->pageNum - 1;
            $links .= "<a href='$url?page=$prev'>上一页</a>";
        }

        if ($this->pageNum < $this->totalPages) {
            $next = $this->pageNum + 1;
            $links .= "<a href='$url?page=$next'>下一页</a>";
        }

        return $links;
    }
}

// 使用示例
$servername = 'localhost';
$username = 'your_username';
$password = 'your_password';
$dbname = 'your_database';

// 创建数据库连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接是否成功
if ($conn->connect_error) {
    die('数据库连接失败: ' . $conn->connect_error);
}

// 查询总记录数
$totalRows = $conn->query('SELECT count(*) as count FROM table')->fetch_assoc()['count'];

// 每页显示5条记录
$pageSize = 5;

// 创建分页对象
$pager = new Pager($totalRows, $pageSize, $conn);

// 查询当前页的数据
$sql = 'SELECT * FROM table';
$result = $pager->getPagerData($sql);

// 显示分页数据
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo $row['content'] . '<br>';
    }
} else {
    echo '没有数据';
}

// 生成分页链接并显示
$url = $_SERVER['PHP_SELF'];
echo $pager->generateLinks($url);

// 关闭数据库连接
$conn->close();
?>
Copy after login

The above code example will obtain paging data from the database, and you can modify it according to actual needs. At the same time, you can freely define pagination styles and link forms to suit your web design.

  1. Conclusion
    By connecting to Baidu Wenxin Yiyan API, we can easily obtain random sentences and display them in paging display. I hope this article will help you understand how to use PHP to connect to the API and implement paging display. Through the introduction of code examples and ideas, I believe you can use it flexibly in actual projects.

The above is the detailed content of How to implement PHP connection to Baidu Wenxin Yiyan API to obtain random statements and display them in pages. 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)

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

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.

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

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.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

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

See all articles