PHP调用OpenDota API:获取前5场Dota2赛事指定数据
Modified PHP Code to Display Top 5 Dota2 Pro Matches in a Table
<?php $url = 'https://api.opendota.com/api/proMatches'; // Request only the 5 most recent pro matches $options = [ "limit" => 5 ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, $url . '?' . http_build_query($options)); $response = curl_exec($ch); // Handle curl request errors if ($response === false) { echo 'Curl Error: ' . curl_error($ch); curl_close($ch); exit; } curl_close($ch); $data = json_decode($response, true); // Validate parsed data if (!is_array($data) || empty($data)) { echo 'Failed to retrieve or process match data.'; exit; } // Render HTML table for the required fields echo '<table border="1" cellpadding="8" cellspacing="0">'; echo '<thead>'; echo '<tr>'; echo '<th>Match ID</th>'; echo '<th>Start Time</th>'; echo '<th>Radiant Team</th>'; echo '<th>Dire Team</th>'; echo '</tr>'; echo '</thead>'; echo '<tbody>'; foreach ($data as $match) { // Convert Unix timestamp to readable date (adjust timezone as needed) $startTime = date('Y-m-d H:i:s', $match['start_time']); // Fallback for missing team names $radiantName = $match['radiant_name'] ?? 'Unknown'; $direName = $match['dire_name'] ?? 'Unknown'; echo '<tr>'; echo '<td>' . htmlspecialchars($match['match_id']) . '</td>'; echo '<td>' . htmlspecialchars($startTime) . '</td>'; echo '<td>' . htmlspecialchars($radiantName) . '</td>'; echo '<td>' . htmlspecialchars($direName) . '</td>'; echo '</tr>'; } echo '</tbody>'; echo '</table>'; ?>
Key Improvements & Fixes:
- Removed Unused Code: The empty
forloop was stripped out as it served no purpose. - Targeted API Request: Replaced the hardcoded filter parameters with
limit => 5to directly fetch only the 5 latest matches from the API (more efficient than fetching 100 results and filtering locally). - Error Handling: Added checks for Curl failures and invalid JSON responses to catch issues early.
- Readable Time Format: Converted the Unix timestamp from the API into a human-readable date string.
- Structured Table Output: Replaced raw
print_rwith a clean HTML table showing only the required fields: Match ID, Start Time, Radiant Team, and Dire Team. - Data Fallbacks: Added safeguards for cases where team names might be missing in the API response, displaying "Unknown" as a default.
内容的提问来源于stack exchange,提问作者Mark Condor
相关产品推荐
相关产品推荐

