如何在PHP中将cURL获取的数据展示为表格
Got it! Since you've already successfully fetched the province data via the API, let's replace that raw var_dump output with a clean HTML table to make it far more readable. Here's how to adjust your code:
Modified Code for Displaying Provinces as a Table
Replace your existing output block with this:
echo "<div style='font-weight: bold;'>getProvinces</div>"; $args = array(); $args["strSessionId"] = $session; $result = CurlFunction($args, "getProvinces"); // First, decode the JSON response if your CurlFunction returns raw JSON // Uncomment this line if needed: // $result = json_decode($result, true); // Check if we have valid province data if (!empty($result) && is_array($result)) { // Render the table echo '<table border="1" cellpadding="8" cellspacing="0" style="border-collapse: collapse; margin-top: 10px; width: 50%;">'; // Table header echo '<thead><tr><th>Province ID</th><th>Province Name</th></tr></thead>'; echo '<tbody>'; // Loop through each province entry foreach ($result as $province) { // Adjust these keys to match your actual API response structure $provinceId = isset($province['id']) ? htmlspecialchars($province['id']) : 'N/A'; $provinceName = isset($province['name']) ? htmlspecialchars($province['name']) : 'N/A'; echo "<tr><td>{$provinceId}</td><td>{$provinceName}</td></tr>"; } echo '</tbody></table>'; } else { echo '<p>No province data available, or the API response format is unexpected.</p>'; }
Key Notes:
- JSON Decoding: If your
CurlFunctionreturns raw JSON text instead of a parsed array, uncomment thejson_decodeline to convert it into a usable PHP array. - Adjust Keys: Tweak
$province['id']and$province['name']to match the actual field names from the API'sgetProvinces.jsonresponse (check your originalvar_dumpoutput to confirm these). - Security: We use
htmlspecialchars()to sanitize the output, preventing potential XSS attacks from untrusted API data. - Styling: The inline CSS adds basic table formatting to ensure the data is clean and easy to scan. You can adjust the width, colors, or borders to match your site's design.
内容的提问来源于stack exchange,提问作者user11224239
相关产品推荐
相关产品推荐

