You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. Removed Unused Code: The empty for loop was stripped out as it served no purpose.
  2. Targeted API Request: Replaced the hardcoded filter parameters with limit => 5 to directly fetch only the 5 latest matches from the API (more efficient than fetching 100 results and filtering locally).
  3. Error Handling: Added checks for Curl failures and invalid JSON responses to catch issues early.
  4. Readable Time Format: Converted the Unix timestamp from the API into a human-readable date string.
  5. Structured Table Output: Replaced raw print_r with a clean HTML table showing only the required fields: Match ID, Start Time, Radiant Team, and Dire Team.
  6. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 22:12:47