2014-04-05 69 views
0

我正在尝试访问API并获取一些JSON。我似乎无法弄清楚我在这里做错了什么。输出为null从URL中检索使用PHP的JSON

这是我的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>'; 
?> 
+0

BTW:我想你不应该公开暴露你的API密钥。 –

+0

我会以任何方式杀死密钥。那不会真的活。是的,这就是我回到php来掩盖它的原因。我可以做到这纯粹是客户端 – soum

回答

1

我做了这个小函数来从几个不同的apis返回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. 
+1

完全合作......感谢您分享此内容。这真的很棒再次感谢 – soum

+0

@soum,没有问题!你能接受答案吗? :)或给我一些爱。大声笑 – xCNPx

2

功能file_get_contentshttps工作。您应该改用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>'; 
?> 
+0

@ Sharanya--这个工作还不错 – soum

+0

接受最早的工作答案是一般习惯,但如果你愿意,你可以自由地选择最迟的答案。 –