chris
chris

Reputation: 36937

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?

Upvotes: 0

Views: 1514

Answers (1)

MrCode
MrCode

Reputation: 64526

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.

Upvotes: 2

Related Questions