• Home
  • PHP
  • MySQL
  • Demos
  • HTML
  • CSS
  • jQuery
  • Framework
  • Social
  • Request Tutorial
PHP Lift
  • Home
  • Demos
  • Advertisement
PHP Lift
  • Home
  • PHP
  • MySQL
  • Demos
  • HTML
  • CSS
  • jQuery
  • Framework
  • Social
  • Request Tutorial
  • Follow
    • Facebook
    • Twitter
    • Google+
    • Pinterest
    • Youtube
    • Instagram
    • 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

How to Extract Text from PDF using PHP PHP
May 17th, 2022

How to Extract Text from PDF using PHP

Is PHP dead in 2021? Is PHP still relevant or worth the effort? PHP
April 3rd, 2022

Is PHP dead in 2021? Is PHP still relevant or worth the effort?

Simple PHP REST API with Slim, PHP & MySQL API
March 3rd, 2022

Simple PHP REST API with Slim, PHP & MySQL

Leave a Reply Cancel reply

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

    Advertisement
    Like us
    Recent Posts
    • How to Extract Text from PDF using PHP
    • 3 reasons why you SHOULD write tests
    • How to create a screen recorder in JavaScript
    • Best 10 Programming Languages that will rule in 2022
    • Top 7 Websites To Get Your First Paid Internship
    Categories
    • API
    • Bootstrap
    • Bot
    • CSS
    • CSS 3
    • Database
    • Designing
    • Framework
    • Guide
    • HTML
    • HTML 5
    • JavaScript
    • jQuery
    • MySQL
    • Node.js
    • oAuth
    • Payment
    • PHP
    • Python
    • Social
    • Tips
    • WordPress
    Weekly Tags
    • PHP
    • How to
    • javascript
    • api
    • MYSQL
    • jQuery
    • PHP Basics
    • Programming Habits
    • HTML5
    • PHP framework
    • About
    • Privacy Policy
    • Back to top
    © PHPLift 2021. All rights reserved.