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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化