phpurlfile-get-contents

Get file content from URL?


When I use following URL in browser then it prompt me to download a text file with JSOn content.

https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World&chof=json

(Click above URL see downloaded file content)

Now I want to create a php page. I want that when I call this php page, it should call above URL and get content(json format) from file and show it on screen.

How can I do this ??


Solution

  • Depending on your PHP configuration, this may be a easy as using:

    $url = 'https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World&chof=json'
    $content = file_get_contents($url);
    

    And then you can process the loaded data. For example, JSON:

    $jsonData = json_decode($content);
    

    However, if allow_url_fopen isn't enabled on your system, you could read the data via CURL as follows:

    <?php
        $curlSession = curl_init();
        curl_setopt($curlSession, CURLOPT_URL, 'https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World&chof=json');
        curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true);
        curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);
    
        $jsonData = json_decode(curl_exec($curlSession));
        curl_close($curlSession);
    ?>
    

    Incidentally, if you just want the raw JSON data, then simply remove the json_decode.