如何将Google Place API评论输出到reviews.php的独立Bootstrap卡片
调整PHP代码输出Bootstrap评论卡片
很简单,我帮你把代码调整成输出独立的Bootstrap卡片,这样每条Google Place的评论都能对应一个美观的卡片组件。下面是具体的修改方案:
1. 修改do_api_call()函数
首先更新你的API调用函数,让它输出完整的Bootstrap卡片结构,同时加入安全处理和更丰富的评论信息:
function do_api_call() { $place_id = get_theme_mod('place_id_setting_field'); // 对place_id进行URL编码,避免特殊字符导致请求错误 $url = "https://maps.googleapis.com/maps/api/place/details/json?placeid=" . urlencode($place_id) . "&key=myapikey"; $data = file_get_contents($url); $rev = json_decode($data, true); // 处理没有评论的情况 if (!isset($rev["result"]["reviews"]) || empty($rev["result"]["reviews"])) { echo '<p class="text-center py-5">暂无评论</p>'; return; } $reviews = $rev["result"]["reviews"]; foreach($reviews as $review) { // 安全转义所有用户生成的内容,防止XSS攻击和HTML混乱 $review_text = htmlspecialchars($review["text"]); $author_name = htmlspecialchars($review["author_name"]); $rating = (int)$review["rating"]; $time_desc = htmlspecialchars($review["relative_time_description"]); // 输出Bootstrap卡片(配合栅格系统实现响应式布局) echo '<div class="col-lg-4 col-md-6 mb-4">'; echo ' <div class="card shadow-sm h-100">'; echo ' <div class="card-body">'; echo ' <div class="d-flex align-items-center mb-3">'; echo ' <h5 class="card-title mb-0">' . $author_name . '</h5>'; echo ' <span class="ms-auto text-warning">'; // 生成星级评分 for ($i=1; $i<=5; $i++) { echo $i <= $rating ? '<i class="bi bi-star-fill"></i>' : '<i class="bi bi-star"></i>'; } echo ' </span>'; echo ' </div>'; echo ' <p class="text-muted small mb-3">' . $time_desc . '</p>'; echo ' <p class="card-text">' . $review_text . '</p>'; echo ' </div>'; echo ' </div>'; echo '</div>'; } }
2. 在reviews.php中调用函数
在reviews.php里,先确保引入Bootstrap的资源(如果你的项目还没引入),然后通过栅格容器包裹评论卡片:
<!-- reviews.php 内容 --> <!-- 引入Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> <!-- 引入Bootstrap Icons(用于星级显示) --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css"> <div class="container py-5"> <h2 class="mb-4 text-center">用户评论</h2> <div class="row g-4"> <?php do_api_call(); ?> </div> </div> <!-- 可选:引入Bootstrap JS,如果你需要用到Bootstrap的交互组件 --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
关键说明
- 响应式布局:用
col-lg-4 col-md-6实现大屏每行3个卡片、中屏每行2个、小屏自动堆叠的效果,你可以根据需求调整栅格类。 - 安全处理:通过
htmlspecialchars()转义所有来自API的用户内容,避免潜在的XSS风险和HTML格式错误。 - 卡片美化:加入了
shadow-sm和h-100类,让卡片更美观且高度统一。 - 错误处理:当API返回无评论数据时,会显示友好的提示文本。
内容的提问来源于stack exchange,提问作者Vladimir Mujakovic




