Patrioticcow
Patrioticcow

Reputation: 27058

how to get json data with curl and php from another domain?

i am triong to do a request to a page and get back some results using curl.

with javascript i could use $.getJSON like so:

$.getJSON('https://ajax.googleapis.com/ajax/services/search/images?q=fuzzy%20monkey&v=1.0&callback=?', function(response) {
    console.log(response.responseData);
});

but in case javascript is not enables i would like to use CURL. im just not sure how.

also i don't necessarily need the response to be json, xml can be ok also

any ideas? Thanks

edit: also i don't really want to use file_get_contents() but pure curl

Upvotes: 1

Views: 3308

Answers (1)

Herbert
Herbert

Reputation: 5778

This returns JSON data from the URL you specified. From the manual.

<?php
        // create curl resource
        $ch = curl_init();

        // set url
        curl_setopt($ch, CURLOPT_URL, "https://ajax.googleapis.com/ajax/services/search/images?q=fuzzy%20monkey&v=1.0");

        //return the transfer as a string
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        // $output contains the output string
        $output = curl_exec($ch);

        // close curl resource to free up system resources
        curl_close($ch);     
?>

It’s entirely up to the host (Google in this case) whether the data returned will be JSON, XML, HTML, etc. You can’t control that unless they provide a means to do so through the API.

mangobug’s link to Getting jSON Data with PHP (curl method) shows you how to send and receive JSON data and how to handle authentication, when necessary.

Upvotes: 3

Related Questions