mercredi 12 juin 2019

How to GET data from API and show it on PHP page?

I want to make a page on my website with some data from an API. The website is made with Wordpress.

I have tried with various codes/functions found on web but with no success.

The API requires me to login by user, pass or token (I prefer token).

I'm new to API and PHP and I don't even know where to start.

If anyone used it before, I want to take data from Exoclick API.

From the API Interface on Exoclick I can see that the request is made with curl, I never used it before and I prefer not to. Here is an example

curl -X GET --header 'Accept: application/json' --header 'Authorization: Bearer tokenhere' 'https://api.exoclick.com/v2/statistics/publisher/country?'

From the API manual, I found this code for login, but placing it in a random page for test, it just crashes my website:

<?php

        // Include Request and Response classes

        $url = 'https://api.exoclick.com/v2/login';

        $params = array(
                'api_token'  => 'tokenhere'
            );

        // Create a new Request object
        $request = new Request($url, 'POST', $params);

        // Send the request
        $request->send();

        // Get the Response object
        $response = $request->getResponse();

        if($response->getStatusCode() == 200) {

            // Retrieve the session token details
            $token = $response->getBodyDecoded();

            print_r($token);
        }
        else {

            echo $response->getStatusCode() . PHP_EOL;
            echo $response->getReasonPhrase() . PHP_EOL;
            echo $response->getBody() . PHP_EOL;
        }
    ?>




Aucun commentaire:

Enregistrer un commentaire