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

Tim Brocklehurst
Tim Brocklehurst used Ask the Experts™
on
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

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
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);
Tim BrocklehurstHead of Digital

Author

Commented:
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

Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Hey Tim,

You have your $auth array setup wrong. When sending headers, you need to send an indexed array of 'key:value' pairs. You're actually sending an associative array of key => value pairs, so instead of:

$auth = array(
    'app_id' => '1234567890',
    'app_key' => '11111111111111111111111111111',
)

you just need:

$auth = array(
    'app_id : 1234567890',
    'app_key : 11111111111111111111111111111',
)

Have a look at the following. This is the approach I'd take so it handles errors a bit nicer:

<?php
$language = "en";
$word = isset($_POST['word']) ? $_POST['word'] : '';

$url = "https://od-api.oxforddictionaries.com/api/v1/inflections/$language/$word";
$auth = [
    'app_id:1234567890',
    'app_key:11111111111111111111111111111',
];

try {

    $response = get_web_page($url, $auth);
    $data = json_decode($response);
    var_dump($data);
    
} catch (Exception $e) {
    die ("Curl Error: " . $e->getMessage());
}

function get_web_page($url, $auth) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $auth);

    $output = curl_exec($ch); 

    if(curl_errno($ch))
        throw new Exception(curl_error($ch));

    return $output;
}

Open in new window

 ** I've edited out your api key details from your previous comment !
Become a Microsoft Certified Solutions Expert

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

Robert SaylorSenior Developer

Commented:
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.
postman example
Tim BrocklehurstHead of Digital

Author

Commented:
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
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
No worries Tim :)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial