Thursday, February 1, 2018

PHP script for Yelp API v3


Yelp provides bearer token with no expiration date when you register your app. Place it in third line.

<?php
 // place your bearer token from Yelp API
 $token = '';
 if($token == "") die ("place your credentials");
 $unsigned_url = "https://api.yelp.com/v3/businesses/search?term=hotel&location=sf&limit=20";
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $unsigned_url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 $headers = [
     'Authorization: Bearer ' . $token
 ];
 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
 $data = curl_exec($ch); // Yelp response
 curl_close($ch);

 // Handle Yelp response data
 $response = json_decode($data);

 // maximal number of API calls reached?
 if(isset($response->error->id) && $response->error->id = "EXCEEDED_REQS") die ("You have reached maximum API calls");
 
 // handle no search results
 if($response->businesses[0]->name == NULL) die ('<h1>No search results match your query.</h1>');

 // dump name, url, location, address, latitude and longitude
 echo"<p>name, url, location, address, latitude and longitude</p>";
 echo"<pre>";
 var_dump(
  $response->businesses[0]->name,
  $response->businesses[0]->url,
  $response->businesses[0]->location->display_address[0],
  $response->businesses[0]->location->display_address[1],
  $response->businesses[0]->coordinates->latitude,
  $response->businesses[0]->coordinates->longitude
 );
?>

No comments:

Post a Comment