使用 PHP 从 URL 检索 JSON


Retrieve JSON using PHP from a URL

我正在尝试使用API并取回一些JSON。我似乎无法弄清楚我在这里做错了什么。我得到null作为输出。

这是我的PHP代码:

<?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>';
?>

函数file_get_contents不适用于https。您应该改用 cURL 函数。

<?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>';
?>

我做了这个小函数来从几个不同的 API 返回 json。你需要使用卷曲。

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;
}

所以你可以做一些类似的事情

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