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

WBOY
Release: 2023-08-25 21:40:02
Original
993 people have browsed it

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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!