【问题标题】:How to get JSON data from Rest API by PHP Curl?如何通过 PHP Curl 从 Rest API 获取 JSON 数据?
【发布时间】:2015-11-17 16:47:23
【问题描述】:

我有一个 Rest api,我可以通过这个 url 访问它:“http://127.0.0.1:8000/api/thesis/?format=json”。现在我想从中获取 JSON 数据。为了连接到 api,我尝试使用 PHP-Curl,如下所示。但我得到NULL! (这是我第一次做 php,任何帮助都会很棒!)

<?php
$service_url = "http://127.0.0.1:8000/api/thesis/?format=json";
//initialize a curl session
$curl = curl_init();
//set options for the transfer
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_TIMEOUT, 5);
curl_setopt($curl, CURLOPT_URL, $service_url);
curl_setopt($curl, CURLOPT_POST, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
//execute the session
$curl_response = curl_exec($curl);
//finish off the session
curl_close($curl);
$curl_jason = var_dump(json_decode($curl_response, true));
print_r($curl_jason);
echo $curl_jason;
?>

【问题讨论】:

  • 你使用的是什么方法 POST 或 GET
  • var_dump($curl_response) 在尝试对其进行 json_decode 之前。你应该看看curl_error
  • 我确定 curl 正在运行(因为我在运行 phpinfo() 时得到 curl 字段)

标签: php api rest php-curl


【解决方案1】:

我认为你应该像这样使用curlGET 方法

$service_url = "http://127.0.0.1:8000/api/thesis/?format=json";
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
//execute the session
$curl_response = curl_exec($curl);
//finish off the session
curl_close($curl);
$curl_jason = json_decode($curl_response, true);
print_r($curl_jason);

【讨论】:

  • 我正在使用 GET 方法,也尝试了您的版本,但我仍然一无所获。
【解决方案2】:

使用下面提到的代码 sn-p 使用 PHP curl

从 REST API 获取数据
 <?php
    function _isCurl(){
        return function_exists('curl_version');
    }    
    if (_iscurl()){
        //curl is enabled
        $url = "http://testDomainName/restAPI.php?id=123&amt=100&jsonp=?";    
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);                               
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($ch);
        curl_close($ch);
        print_r($output);
       // Curl operations finished            
    }
    else{
        echo "CURL is disabled";
    }
    ?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-09
    • 2017-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多