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

报告相同问题?

悬赏问题

  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签)
  • ¥50 sft下载大文阻塞卡死
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失
  • ¥15 springboot+vue 集成keycloak sso到阿里云
  • ¥15 win7系统进入桌面过一秒后突然黑屏
  • ¥30 backtrader对于期货交易的现金和资产计算的问题
  • ¥15 求C# .net4.8小报表工具
  • ¥15 安装虚拟机时出现问题