我有一个小网站 jamesmcnee.co.uk,它的页面加载时间相当长。加载页面可能需要长达 8 - 12 秒的时间。我认为这与我创建的PHP有关,以便与Steam API进行交互。我有这些文件:
-
SteamWidget.php:
$api = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=". $key ."&steamids=76561198014955377&format=json"; $json = file_get_contents($api); $schemaProfile = json_decode($json, true); $api = "http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=". $key ."&steamid=76561198014955377&format=json"; $json = file_get_contents($api); $schemaGames = json_decode($json, true); echo '<div id="sideSteamProfile">'; echo '<h2>On Steam</h2>'; echo '<img src="'; echo $schemaProfile['response']['players'][0]['avatarfull']; echo '" alt="Steam Avatar Icon" />'; echo '<p>Steam Name:<a href="'; echo $schemaProfile['response']['players'][0]['profileurl']; echo '">'; echo $schemaProfile['response']['players'][0]['personaname']; echo '</a></p>'; if($schemaProfile['response']['players'][0]['personastate'] == "0"){ echo '<p>Currently: <font color="red">Offline</font></p>'; } else{ echo '<p>Currently: <font color="green">Online</font></p>'; } echo '<p>Last Online:'; echo gmdate("d-m-Y H:i", $schemaProfile['response']['players'][0]['lastlogoff']); echo '</p>'; echo '<p>Number of Games:'; echo $schemaGames['response']['game_count']; echo '</p>'; echo '<p>Most Played Game:'; echo getMostPlayed(); echo '</p>'; echo '<p>Total Hours:'; echo getHoursPlayed(); '</p>'; echo '</div> <!-- Closes the sideSection div -->'; ?>
第二个叫做MostPlayed.php:
<?php
include 'ApiKey.php';
function getMostPlayed()
{
$GameWithMostHours = "None";
$api = "http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=". $key ."&steamid=76561198014955377&format=json";
$json = file_get_contents($api);
$schemaGames = json_decode($json, true);
$NumberOfGames = $schemaGames['response']['game_count'];
$CurrentlyHighestHours = 0;
for ($x = 0; $x < $NumberOfGames; $x++){
$CheckHighest = $schemaGames['response']['games'][$x]['playtime_forever'];
if ($CheckHighest > $CurrentlyHighestHours){
$CurrentlyHighestHours = $CheckHighest;
$GameWithMostHours = $schemaGames['response']['games'][$x]['name'];
}
}
return $GameWithMostHours;
}
function getHoursPlayed()
{
$api = "http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=". $key ."&steamid=76561198014955377&format=json";
$json = file_get_contents($api);
$schemaGames = json_decode($json, true);
$NumberOfGames = $schemaGames['response']['game_count'];
$TotalNumberOfHours = 0;
for ($x = 0; $x < $NumberOfGames; $x++){
$TotalNumberOfHours += $schemaGames['response']['games'][$x]['playtime_forever'];
}
$TotalNumberOfHours = sprintf("%02dh %02dm", floor($TotalNumberOfHours/60), $TotalNumberOfHours%60);
return $TotalNumberOfHours;
}
?>
所以两个简单的PHP文件,那么为什么要提高加载速度。正如我提到的,我认为这与我正在使用的 for 循环有关,但我看不到另一种方法可以做到这一点,并且在另一种语言(如 JAVA)中,这些循环需要几分之一秒。任何建议不胜感激!
谢谢詹姆斯·麦克尼。
加载页面而不执行对该 API 的调用。让在文档上运行的 AJAX 调用准备好获取数据、处理数据并返回要显示的 html 的脚本。