0

I am trying to hit an API and get some JSON back. I can’t seem to figure out what I am doing wrong here. I am getting null as the output.

Here is my PHP code:

<?php

$query_string_full = 'https://api.cityofnewyork.us/calendar/v1/search.htm?app_id=39563317lalaland&app_key=somethingsomething&categories=City%20Government%20Office';

$json = file_get_contents($query_string_full);
$obj = json_decode($json);
echo '<pre>'. json_encode($obj, JSON_PRETTY_PRINT) .'</pre>';
?>
2
  • BTW: I think you should not expose your API key publicly. Commented Apr 5, 2014 at 0:52
  • I will kill that key any way. That wont really live. Yeah, thats the reason I am falling back on php to mask it. I could do this purely client side Commented Apr 5, 2014 at 0:53

2 Answers 2

2

The function file_get_contents doesn’t work with https. You should use the cURL functions instead.

<?php
$query_string_full = 'https://api.cityofnewyork.us/calendar/v1/search.htm?app_id=39563317&app_key=8396021a9bde2aad2eaf8ca9dbeca353&categories=City%20Government%20Office';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $query_string_full);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$json = curl_exec($ch);
curl_close($ch);

$obj = json_decode($json);
echo '<pre>'. json_encode($obj, JSON_PRETTY_PRINT) .'</pre>';
?>
Sign up to request clarification or add additional context in comments.

1 Comment

It’s the general custom to accept the earliest working answer but you have every liberty to go for a late answer if you like.
1

I made this little function to return the json from a few different apis. You need to be using curl.

function exposeJSON ($apiUrl) {
    $json_url = $apiUrl;

    $ch = curl_init();

    // set URL and other appropriate options
    curl_setopt($ch, CURLOPT_URL, $json_url);

    // Built in authentication if needed.
    //curl_setopt($ch, CURLOPT_USERPWD, "$USER:$PASS");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);

    // grab URL and pass it to the browser
    $response = curl_exec($ch);
    $return = json_decode($response[0], true);

    // close cURL resource, and free up system resources
    curl_close($ch);

    return $return;
}

So you could do something like

$apiData = exposeJSON('urltoapi');
echo $apiData; // Should be the json. 

1 Comment

totally worked...thanks for sharing this. This is really great Thanks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.