I am making a website for a gaming group and they would like to add their guild information on their website using the API the game developers provide. The APIs I'm working with are the following:
https://wiki.guildwars2.com/wiki/API:1/item_details https://wiki.guildwars2.com/wiki/API:2/guild/:id/treasury
Right now, I have a table to show what items are in the treasury, how many, and how many are needed. It looks like this:
Item name | Quantity | Needed
-----------------------------------------------------
Iron Ore | 150 | 1500
Mithril Ingot | 134 | 1000
etc...
And this is my PHP code:
// This gets a particular item.
function getItem($id) {
$response = file_get_contents("https://api.guildwars2.com/v1/item_details.json?item_id=".$id);
$response = json_decode($response, false);
return $response;
}
// This gets the name if item 123
// echo getItem(123)->name;
// Begin table.
echo '<table class="table table-striped">';
$treasuryItem = file_get_contents('https://api.guildwars2.com/v2/guild/B95A3B40-A764-4648-8EE6-39549E922A99/treasury?access_token=358AC6CB-0596-D64F-88D5-5CFA9AA27AAA273F3C6A-BC9E-47EE-AA28-63565C3EFEEE');
$treasuryItem = json_decode($treasuryItem);
foreach($treasuryItem as $key => $treasuryItem) {
echo '<tr>';
echo '<td>'.getItem($treasuryItem->item_id)->name.'</td>'; // This is where I think the trouble lies.
echo '<td>'.$treasuryItem->count.'</td>';
echo '<td>';
foreach($treasuryItem->needed_by as $key => $treasuryItem) {
echo $treasuryItem->count.'<br />';
}
echo '</td>';
echo '</tr>';
}
echo '</table>';
As it stands now, it works and the info is displayed as I'd like it to be. My problem is that it takes a very long time for the page to load. I think the problem is that the function that calls the Item API file is being looped in the foreach
statement. What alternative method can I use to prevent this from happening?
The Link to the Items seems public, and i thing items wont change after set up. Maybe they change after a patch or so.
If you keep that in mind, you can hold the informations on your server. Change the function to this:
function getItem($id,$forceDownload=false) {
$response=null;
$file = "item{$id}.json";
if(!file_exists($file) || $forceDownload){
$response = file_get_contents("https://api.guildwars2.com/v1/item_details.json?item_id=".$id);
file_put_contents($file,$response);
}
if(!$response){
$response = file_get_contents($file);
}
return json_decode($response, false);
}
Now for each Item a file would be saved e.g. item123.json
, next time on pageload it will not be fetched from the WEB again, instead it uses the given file. That will be quit faster then.
If you want to reload all files from WEB use the second parameter $forceDownload
and set it to true
. Then all files will be loaded again.
And maybe set up a better dir like "../items/item{$id}.json"