The page is assigning $gid
to the url paramater gid. It then reads an XML file that looks like this:
<games>
<game>
<name>name 1</name>
<appID>1234</appID>
</game>
<game>
<name>name 2</name>
<appID>5678</appID>
</game>
</games>
The code I am using works correctly but takes a second to load because there are so many <game>
elements on the list. Is there are more efficient way to go about foreach? Here is the code:
$gid = (int) $_GET['gid'];
$gamespage = simplexml_load_file("http://gamepage.com/games?xml=1");
$games = $gamespage->games;
foreach ($games->game as $game) {
if ($gid == $game->appID) {
$appid = $game->appID;
$gamename = $game->name;
}
}
echo $gid, "<br />";
echo $appid, "<br />";
echo $gamename;
2 Answers 2
Add a break
to that if
statement to stop looping once you've found the correct node.
Probably the only thing you can do to make it faster is to limit the number of results returned at one time. Could you maybe use pagination or something? Is there a reason you need to get all of them at once? Even if it was coming from a database, if there were enough records, it would take a couple seconds to get ALL of them. I'd do, for example, 50 per page.
foreach
loop, but because you're fetching all of the data from a remote server every single time. \$\endgroup\$