1

I have a Rest api which I can access by this url: "http://127.0.0.1:8000/api/thesis/?format=json". Now I want to get the JSON data from it. For connecting to the api I tried to use PHP-Curl as below. But I get NULL! (This is the first time I'm doing php any help will be great!)

<?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;
?>
3
  • what method you are using POST or GET Commented Aug 24, 2015 at 9:55
  • var_dump($curl_response) before trying to json_decode it. You should have a look at curl_error. Commented Aug 24, 2015 at 9:56
  • I'm sure curl is running (because I get the curl field when I run the phpinfo() ) Commented Aug 24, 2015 at 11:41

2 Answers 2

4

I think you should use GET method of curl like this

$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);
Sign up to request clarification or add additional context in comments.

1 Comment

I'm using GET method and, tried your version also but I still get nothing.
1

Use the below mentioned code snippet to fetch data from a REST API using PHP curl

 <?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";
    }
    ?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.