如何将API获取的JSON数据以表格/Bootstrap格式循环展示?
Displaying Country API Data as HTML/Bootstrap Table
First, your current PHP script outputs raw JSON data. To display this in a structured table, you’ll need to decode the JSON into a PHP array, then loop through the data to generate table rows. Here’s a step-by-step solution:
Step 1: Update PHP to Decode the JSON Response
Modify your script to parse the JSON instead of echoing the raw string. This lets you work with the data as a PHP array:
<?php $curl = curl_init(); curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'api-key: 1234', 'Content-Type: application/json', 'Accept: application/json' )); curl_setopt ($curl, CURLOPT_URL, 'https://api.com/api/v3/countries'); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec ($curl); if ($response === false) { die('Error fetching data: ' . curl_error($curl)); } curl_close ($curl); // Decode JSON into an associative array $countryData = json_decode($response, true); // Fallback to empty array if "countries" key is missing $countries = $countryData['countries'] ?? []; ?>
Step 2: Render as a Basic HTML Table
Add this code after the PHP script to generate a standard, unstyled table:
<table border="1" cellpadding="8" cellspacing="0"> <thead> <tr> <th>Country Name</th> <th>3-Letter Code</th> <th>2-Letter Code</th> </tr> </thead> <tbody> <?php foreach ($countries as $country): ?> <tr> <td><?php echo htmlspecialchars($country['name']); ?></td> <td><?php echo htmlspecialchars($country['code3']); ?></td> <td><?php echo htmlspecialchars($country['code']); ?></td> </tr> <?php endforeach; ?> </tbody> </table> <p>Total countries returned: <?php echo $countryData['total'] ?? 0; ?></p>
Step 3: Render as a Styled Bootstrap Table
For a polished, responsive table using Bootstrap, first include the Bootstrap CSS in your page’s <head>:
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
Then use Bootstrap’s table classes to style your output:
<div class="container mt-4"> <table class="table table-striped table-hover table-bordered"> <thead class="table-dark"> <tr> <th>Country Name</th> <th>3-Letter Code</th> <th>2-Letter Code</th> </tr> </thead> <tbody> <?php foreach ($countries as $country): ?> <tr> <td><?php echo htmlspecialchars($country['name']); ?></td> <td><?php echo htmlspecialchars($country['code3']); ?></td> <td><?php echo htmlspecialchars($country['code']); ?></td> </tr> <?php endforeach; ?> </tbody> </table> <p class="text-muted">Total countries: <?php echo $countryData['total'] ?? 0; ?></p> </div>
Important Notes:
- We use
htmlspecialchars()to escape special characters in the API data, preventing potential XSS attacks. - The
??null coalescing operator handles cases where the API response might missing expected keys (like if the API returns an error). - Bootstrap classes like
table-striped,table-hover, andtable-darkadd styling without writing custom CSS.
内容的提问来源于stack exchange,提问作者user9804375
相关产品推荐
相关产品推荐

