PHP连接百度文心一言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; ?>
<?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(); ?>
以上代码示例将从数据库中获取分页数据,你可以根据实际需求进行修改。同时,你可以自由定义分页样式和链接形式,以适应你的网页设计。
以上是PHP连接百度文心一言API获取随机语句并进行分页展示的实现方式的详细内容。更多信息请关注PHP中文网其他相关文章!