php cURL post to external domain and work with response

Ok this may be a simple question. I have a working concept of posting to the external domain and getting it to work with the post to do what i want and need it to do. However. I need it to after doing what I want it to do output a JSON response that I can in turn work with the domain of origin. I know with cURL I should be able to grab whats output but Im not sure how to work it into what I have, as this was initially given to me by someone else to work with and I am not extremely familiar with cURL

this is what I have thus far that works to post to the domain.

$url = 'http://thedomain.com/new/';
        $fields = array(
                    'api'=>'randomkey',
                    'id'=>'100000',
                    'url'=>urlencode($longurl),
                );

    //url-ify the data for the POST
    $fields_string = '?';
    foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
    rtrim($fields_string,'&');

    //open connection
    $ch = curl_init();

    //set the url, number of POST vars, POST data
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_POST,count($fields));
    curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

    //execute post
    $result = curl_exec($ch);

    //close connection
    curl_close($ch);

how can I alter this to take what the external site would spit out in JSON form and have it so I can work with it from the domain I am working with?

Answers


You are missing the RETURNTRANSFER option which tells cURL to return the response to your $result:

curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);

Now that you have the response you can manipulate it and json_encode() then output it as needed.


Need Your Help

How to setup CHelper and configure on IntelliJ?

java plugins intellij-idea

I tried for last two days. But I always draw a blank. I have trouble in setting up the project, and adding dependencies - and creating tasks - it always shows some error or the other.

RStudio: git add --all from the UI

r git rstudio

I would like to understand if I am missing anything here, and if not, this is a feature request for RStudio.