Link to home
Start Free TrialLog in
Avatar of Tim Brocklehurst
Tim BrocklehurstFlag for United Kingdom of Great Britain and Northern Ireland

asked on

How to use cURL in PHP to get json response from api call.

I'm trying to work with the Oxford Dictionary api to check whether words discovered in my app do actually feature in the dictionary.
Usually I make api calls using jquery and ajax, however this one doesn't receive client-side calls so I'm having to write it server-side in PHP and fire it using ajax from a javascript function.

I'm close, but I can't quite see how to include the authentication parameters in the url call, and my PHP is a bit sketchy at the best of times, so I'm hoping an expert here can help me to get the syntax right. At the moment, the response from the PHP file is simply: "Authentication parameters missing."  - So I'm sure its just my own ignorance about php and cURL holding it back. Can you help by showing me what changes to make in the PHP file below?

Any advice would be warmly received. Thanks...

This is how it looks so far:

For the JS:
function isDictionaryWord(pl){
    
    var isWord = false;
    
    pl = pl.toLowerCase();
    pl = pl.split(' ').join('_');
    
    $.ajax({
            url: "call_oxford_apia.php", 
            method: "post",
            data: { "word":pl},
                success: function(resp){
                    console.log("Oxford Check Shows: " + JSON.stringify(resp))
                    isWord = true;
                },
                 error: function() {
                     isWord = false;
                } 
    });
    
    return isWord;
}

Open in new window


And for the PHP: (filename: 'call_oxford_apia.php')

<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');

$language = "en";
$word = $_POST['word'];
$auth = array('app_id'=>'1234',
                    'app_key'=>'12345678910',
                    'Accept'=>'application/json');

$response = get_web_page("https://od-api.oxforddictionaries.com/api/v1/inflections/".$language.'/'.$word);
$resArr = array();
$resArr = json_decode($response);
echo $resArr;

function get_web_page($url) {

    $ch = curl_init($url);
        curl_setopt($curl, CURLOPT_URL,$url);
        curl_setopt ($curl, CURLOPT_POST, 1); 
        
        curl_setopt ($curl, CURLOPT_POSTFIELDS,  http_build_query($auth)); 
        curl_setopt($curl, CURLOPT_HTTPHEADER,$auth);
        
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

    $content  = curl_exec($ch);

    curl_close($ch);

    return $content;
}

?>

Open in new window

Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

You're declaring your $auth variable outside of the function, so it's not available inside the function. Either declare it inside, or pass it in as a parameter:

$response = get_web_page("https://od-api.oxforddictionaries.com/api/v1/inflections/".$language.'/'.$word, $auth);
$resArr = array();
$resArr = json_decode($response);
echo $resArr;

function get_web_page($url, $auth) {
   ...
}

If your turn on error reporting, you'd probably see your error. Add this to the top of your script:

error_reporting(E_ALL);
ini_set('display_errors', 1);
Avatar of Tim Brocklehurst

ASKER

Thanks Chris - that's really helpful.
Especially appreciate the heads-up about passing variables correctly to the php function. I also added the error_reporting to the top of the file as you suggested.

I've been working on it more, with your advice and also with further reading, and have modified the php file to the following. However, in its present state, it still tells me authentication parameters are missing.

Following is the PHP code, and this is a link to the Oxford Dictionary documentation (in case it helps) ... you'll see there's no examples given in PHP, but perhaps you're able to fathom what's required better than I can.

Incidentally, you'll notice most of the curl options in the array below have been commented out. I have tried with each of them enabled in turn but still get the same result.

This is the output in my browser console:

Authentication parameters missing | Error no.0 | Curl Error: 1

Open in new window



<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');

$language = "en";
$word = $_POST['word'];

$auth = array('app_id'=>'1234567890',
                'app_key'=>'111111111111111111111111111111',
                'Accept'=>'application/json');
$response = get_web_page('https://od-api.oxforddictionaries.com/api/v1/inflections/'.$language.'/'.$word,$auth);
$resArr = array();
$resArr = json_decode($response);
echo $resArr;

function get_web_page($url,$auth) {
        
        $pFields = http_build_query($auth);
        $ch = curl_init($url);
        $options = array(
                //CURLOPT_RETURNTRANSFER => true,         // return web page
                //CURLOPT_HEADER         => false,        // don't return headers
                //CURLOPT_FOLLOWLOCATION => false,         // follow redirects
                //CURLOPT_ENCODING       => "utf-8",           // handle all encodings
                //CURLOPT_AUTOREFERER    => true,         // set referer on redirect
                //CURLOPT_CONNECTTIMEOUT => 20,          // timeout on connect
                //CURLOPT_TIMEOUT        => 20,          // timeout on response
                //CURLOPT_POST            => 1,            // i am sending post data
                CURLOPT_POSTFIELDS     => $pFields,    // this are my post vars
                CURLOPT_SSL_VERIFYHOST => 0,            // don't verify ssl
                CURLOPT_SSL_VERIFYPEER => false,        //
                CURLOPT_VERBOSE        => 1,
                CURLOPT_HTTPHEADER     => $auth
                );
                
        curl_setopt_array($ch,$options);
        $data = curl_exec($ch);
        $curl_errno = curl_errno($ch);
        $curl_error = curl_error($ch);
        echo " | Error no.".$curl_errno;
        echo " | Curl Error: ".$curl_error;
        curl_close($ch);
        return $data;

}

?>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I would use postman, test and develop the API call there then export it to the codebase you need. PHP Curl.

Then json_decode the results.
User generated image
Yes Chris - your code was much better organised than mine. And did the trick precisely. Thank you. (And thanks too for editing out my careless api entries...!).

Robert - many thanks for the heads-up about Postman... I have looked into that and I'm sure it will be useful for future projects.

Thanks again
Tim
No worries Tim :)