簡體   English   中英

如何通過PHP Curl從Rest API獲取JSON數據?

[英]How to get JSON data from Rest API by PHP Curl?

我有一個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;
?>

我想你應該像這樣使用curl GET方法

$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);

使用下面提到的代碼片段使用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";
    }
    ?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM