使用PHP从URL检索JSON

时间:2014-04-05 00:49:17

标签: php json file-get-contents

我正在尝试使用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>';
?>

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

我做了这个小功能,从几个不同的apis返回json。你需要使用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;
}

所以你可以做类似

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