• PHP
  • MySQL
  • Demos
  • HTML
  • CSS
  • jQuery
  • Framework
  • Social
  • Request Tutorial
PHP Lift
  • Home
  • Demos
  • PHP Jobs
  • Advertisement
PHP Lift
  • PHP
  • MySQL
  • Demos
  • HTML
  • CSS
  • jQuery
  • Framework
  • Social
  • Request Tutorial
  • Follow
    • Facebook
    • Twitter
    • Google+
    • Youtube
    • RSS
Working with APIs in PHP
Home
Social

Working with APIs in PHP

February 13th, 2017 Ivan Dimov API, PHP, Social 0 comments

Facebook Twitter Google+ LinkedIn Pinterest

Let us say that we want to use the OpenWeatherMap API to display the weather in an arbitrary city. We could achieve this in the following way:

$data = file_get_contents("http://api.openweathermap.org/data/2.5/weather?q=" . urlencode($city) . "&APPID=YOURAPPID&units=metric");

$data = json_decode($data);

$out = $city . ":\nWeather Condition:  *" . $data->weather[0]->main . "*\nCurrent Temperature: *" . $data->main->temp . "* degrees\n";

If we want to get the latest photos for a certain user in Instagram, choose a random one, and print the URL to it we could again do the following:

 $media = @file_get_contents("https://www.instagram.com/" . trim($theUser) . "/media/");

 $media = json_decode($media);

 $randomImage = $media->items[mt_rand(0, count($media->items) - 1)]->images->standard_resolution->url;

 echo $randomImage;

Those APIs are simple enough in that it lets us make a simple GET request, passing some parameters, JSON decode their output and display or process the data in any way we want and file_get_contents is enough to achieve the desired communication.

Something more complicated would be to make a GET request to an API that actually returns a redirect to an image (with cat gifs) when we actually want to get is the redirection URL. Instead of file_get_contents, we can use curl in the following way for that purpose:

function kittens() {

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, "http://thecatapi.com/api/images/get?format=src&type=gif");

    curl_setopt($ch, CURLOPT_HEADER, true);

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    curl_exec($ch);

    $url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

    echo json_encode(array("text" => $url));

}

Many APIs implement OAuth authorization to work with them, such as Facebook. Therefore, they have made their own pieces of libraries that facilitate interaction with them. Here is how to use the Facebook PHP SDK to post to a page:

First, we get an access token that we use to identify ourselves to Facebook and perform actions on behalf of a certain entity.

$app_secret = FB_APP_SECRET;

                        FacebookSession::setDefaultApplication(FB_APP_ID, $app_secret);

                        $access_token = FB_ACCESS_TOKEN;

                        $session = new FacebookSession($access_token);

                        FacebookSession::enableAppSecretProof(false);

                        $page_id = FB_PAGE_ID;

                        $access_token = (new FacebookRequest($session, 'GET', '/' . $page_id, array('fields' => 'access_token')))

                                        ->execute()->getGraphObject()->asArray();

Thereafter, we use the SDK to make a POST request, sending the $message variable as a status in the Facebook page, corresponding to the $page_id in the URL of the endpoint.

 $access_token = $access_token['access_token'];

                        $request = (new FacebookRequest(

                                $session, 'POST', '/' . $page_id . '/feed', array(

                            'access_token' => $access_token,

                            'message' => $message

                        )));

                        $response = $request->execute();

                        $graphObject = $response->getGraphObject();

Many APIs rely on Oauth besides Facebook, and the communication resembles the following pattern.

APIs have great value as they can help programmers save time by not starting everything from scratch and by outsourcing certain side-needs of their applications. There are numerous websites that list available APIs with which you can do cool things, one which I like to browse is: https://market.mashape.com/explore

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)

Related

  • Tags
  • api
  • PHP
Facebook Twitter Google+ LinkedIn Pinterest
Next article Working with dates in PHP and JavaScript
Previous article Useful PHP built-in functions

Ivan Dimov

Ivan is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling. You can find more about him at: http://www.dimoff.biz. facebook, twitter

Related Posts

Stripe Payment Gateway Charge Credit Card with PHP API
February 15th, 2021

Stripe Payment Gateway Charge Credit Card with PHP

6 Reasons Laravel is the Top PHP Framework in the Web Development Industry Framework
February 1st, 2021

6 Reasons Laravel is the Top PHP Framework in the Web Development Industry

12 Reasons to Choose PHP for Developing Website Guide
November 17th, 2020

12 Reasons to Choose PHP for Developing Website

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Advertisement
Recent Posts
  • Stripe Payment Gateway Charge Credit Card with PHP
  • How to building responsive WordPress theme using Bootstrap
  • 6 Reasons Laravel is the Top PHP Framework in the Web Development Industry
  • 9 Best Programming languages you should learn in 2021
  • 12 Reasons to Choose PHP for Developing Website
Categories
  • API
  • Bootstrap
  • CSS
  • CSS 3
  • Designing
  • Framework
  • Guide
  • HTML
  • HTML 5
  • JavaScript
  • jQuery
  • MySQL
  • Node.js
  • oAuth
  • Payment
  • PHP
  • Python
  • Social
  • Tips
  • WordPress
Weekly Tags
  • PHP
  • api
  • How to
  • PHP Basics
  • Programming Habits
  • HTML5
  • PHP framework
  • Download
  • laravel
  • css
  • About
  • Privacy Policy
  • Back to top
© PHPLift 2020. All rights reserved.