如何用PHP通过REST API获取并解析国家数据
处理REST Countries API数据并生成卡片网格布局
你当前的cURL代码直接把JSON输出到页面了,得先把数据抓下来解析成PHP能处理的数组,再提取需要的字段,最后循环生成卡片布局,直接看实操代码和说明:
第一步:修改cURL代码,解析JSON数据
把原来直接输出JSON的逻辑改成捕获数据、解析成PHP数组:
<?php // 创建cURL资源 $ch = curl_init(); // 设置请求选项,重点加返回内容转变量的配置 $options = [ CURLOPT_URL => 'https://restcountries.com/v3.1/all', CURLOPT_HEADER => false, CURLOPT_RETURNTRANSFER => true, // 关键:让curl返回内容而非直接输出 ]; curl_setopt_array($ch, $options); // 获取API返回的JSON字符串 $jsonData = curl_exec($ch); // 关闭cURL资源 curl_close($ch); // 解析JSON为PHP关联数组,第二个参数true转成数组而非对象 $countries = json_decode($jsonData, true); // 处理解析失败的情况 if ($countries === null) { die('JSON解析失败,请检查API链接或网络'); } ?>
第二步:提取数据并生成卡片网格
REST Countries API的返回结构里,常用国家名存在['name']['common'],国旗SVG链接在['flags']['svg'],首都在['capital'][0](部分国家有多个首都,取第一个即可)。用foreach循环遍历数组,配合HTML+CSS生成响应式卡片网格:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>国家数据展示</title> <style> /* 网格容器样式 */ .countries-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 20px; padding: 20px; max-width: 1200px; margin: 0 auto; } /* 卡片样式 */ .country-card { border: 1px solid #eee; border-radius: 8px; padding: 16px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); text-align: center; transition: box-shadow 0.2s; } .country-card:hover { box-shadow: 0 4px 8px rgba(0,0,0,0.15); } .country-flag { width: 100px; height: 60px; object-fit: contain; margin-bottom: 12px; } .country-name { font-size: 18px; font-weight: bold; margin-bottom: 8px; } .country-capital { color: #666; } </style> </head> <body> <div class="countries-grid"> <?php foreach ($countries as $country): ?> <div class="country-card"> <img src="<?= $country['flags']['svg'] ?>" alt="<?= $country['name']['common'] ?> 国旗" class="country-flag"> <div class="country-name"><?= $country['name']['common'] ?></div> <div class="country-capital"> <?= isset($country['capital']) ? '首都:' . $country['capital'][0] : '无首都' ?> </div> </div> <?php endforeach; ?> </div> </body> </html>
关键细节说明:
- 用
isset($country['capital'])判断字段是否存在,避免部分无首都的国家(如瑙鲁)引发报错 - CSS的
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr))实现响应式布局,屏幕大小变化时自动调整卡片数量 - 加了hover阴影效果提升交互体验
把上面两段代码合并到同一个PHP文件,运行后就能看到排版整齐的国家卡片网格了。
内容的提问来源于stack exchange,提问作者Diggity Doggity
相关产品推荐
相关产品推荐

