How to make this php page load faster

667 Views Asked by At

I am working on a php page that basically connects to Harvest using the Harvest API and fetches some Information. The code basically returns all the user objects in Harvest and calculates the expenses for each user. It takes around 50 seconds to load. Please see my code below-

<?php require_once( 'connection.php' );
  $result= $api->getUsers();
  $users=$result->data;



  $range= Harvest_Range::lastMonth();


  foreach($users as $key=>$value){

 $user_id=$value->get("id");
 $first_name=$value->get("first-name");
 $last_name=$value->get('last-name'); 

  $result_expenses=$api->getUserExpenses($user_id, $range);
 $expenses_data=$result_expenses->data;

 $total_cost=0;

foreach($expenses_data as $key=>$value){
if($value->get("is-locked")=="true"){
$total_cost=$total_cost+$value->get("total-cost");

}} 
 ?>
 <?php if($total_cost!=0){?>
 <tbody>
 <tr>
 <td> <?php echo $first_name; echo " ".$last_name; ?> </td>
 <td> $ <?php echo $total_cost; ?> </td>
 </tr>
 </tbody>
 <?php }}?>

 </table>

Is there any way to make the page load faster?

1

There are 1 best solutions below

0
On

Your page is slow because you are requesting data for each user, one at a time. This means that as you get more users you are going to have to make more requests. More requests means your application will take longer and longer.

Unfortunately it appears you are only able to request data from one user at a time: http://mdbitz.com/docs/harvest-api/

If you are able to store the data locally you could greatly increase the speed of your application. You can store it anywhere that is easily accessible such as a database, cache or even a text file. Then you will need to determine how often you update your local copy from the Harvest API to get the latest data.