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

Working with APIs in PHP

June 16th, 2025 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 X (Opens in new window) X
  • Click to share on Facebook (Opens in new window) Facebook

Related

  • Tags
  • api
  • PHP
Facebook Twitter Google+ LinkedIn Pinterest
Next article Using the PayPal Payments API with PHP and Guzzle
Previous article Create Live Search in HTML table with jQuery

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

Useful PHP built-in functions PHP
June 18th, 2025

Useful PHP built-in functions

How do you create subdomains dynamically using PHP when a user signs up? PHP
June 18th, 2025

How do you create subdomains dynamically using PHP when a user signs up?

Useful Laravel functions and methods, Part-1 Framework
June 18th, 2025

Useful Laravel functions and methods, Part-1

Leave a Reply Cancel reply

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

Subscribe
Get new posts by email:
Powered by follow.it
Advertisement
Like us
Recent Posts
  • 9 Best Programming languages you should learn in 2021
  • What is Progressive Web Applications and Why Create a PWA?
  • 7 HTML attributes that you must learn today!
  • Why Use MongoDB and When to Use It?
  • Introduction to Git for version control
Categories
  • API
  • Bootstrap
  • Bot
  • CSS
  • CSS 3
  • Database
  • Designing
  • Framework
  • Guide
  • HTML
  • HTML 5
  • JavaScript
  • jQuery
  • Laravel
  • MySQL
  • Node.js
  • oAuth
  • Payment
  • PHP
  • Python
  • Social
  • Tips
  • Web 3.0
  • WordPress
Weekly Tags
  • PHP
  • How to
  • javascript
  • laravel
  • MYSQL
  • PHP framework
  • css
  • jQuery
  • HTML to PDF
  • Web Development
  • About
  • Privacy Policy
  • Back to top
© PHPLift.net. All rights reserved.