Question

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>';
?>
Was it helpful?

Solution 2

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. 

OTHER TIPS

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>';
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top