doujiao9866 2014-04-05 00:49
浏览 43
已采纳

使用PHP从URL检索JSON

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条回答 默认 最新

  • dongzun9958 2014-04-05 00:54
    关注

    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条)

报告相同问题?

悬赏问题

  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持