I have a site that is going to show businesses near the user. It uses Google APIs to do this. It first grabs nearby businesses using the radar search, grabs the place_id and saves it into the database(which I will need later) and then uses the place ID to grab details about the place. If certain criteria is met, then it displays the results in a table. However, it is taking a long time to load and I am trying to figure out why. If it is just too much information and that's the way it has to be then fine, but I feel like I am doing something inside the code to slow it down more than it should.
<?php
$xml = simplexml_load_file("https://maps.googleapis.com/maps/api/place/radarsearch/xml?location=39.53,-89.33&radius=10000&type=establishment&key=MYKEY") or die("Error: Cannot create object");
foreach($xml->result as $get)
{
if($i==7) break;
$xml2 = simplexml_load_file("https://maps.googleapis.com/maps/api/place/details/xml?placeid=" . $get->place_id . "&key=MYKEY") or die("Error: Cannot create object");
$sql = "SELECT * FROM Places WHERE GoogleID = '".$get->place_id."'";
$records = $conn->query($sql);
$grab = $records->fetch_assoc();
if($records->num_rows > 0)
{
//yay
}
Else
{
$MakeNew = "INSERT INTO Places (GoogleID, ConfirmedHiring) VALUES ('".$get->place_id."', 'No')";
if(mysqli_query($conn, $MakeNew))
{
$records = $conn->query($sql);
$grab = $records->fetch_assoc();
}
}
foreach($xml2->result->address_component as $item){if($item->type == "locality"){$placecity = $item->long_name;}}
echo "<tr>";
echo "<td data-title='Business'>" . $xml2->result->name . "</td>";
echo "<td data-title='Location'>" . $placecity . "</td>";
echo "<td data-title='Confirmed Hiring'>" .$grab["ConfirmedHiring"]. "</td>";
echo "</tr>";
$i++;
}
?>
If you used a nearby search instead of a radar search, you wouldn't have to get the place details separately afterwards, the results would contain all of the details already. If that's not an option and you need to do radar search, you could at least do all of the details requests in parallel.
Similarly, you could select all of the matching records from the DB using an IN
query instead of selecting them one at a time, and you could insert all of the ones that are found to be missing with a single query as well.
Finally, if something is slow, use a profiler to find out why it's slow; it's faster and more reliable than asking the internet.