Get file content from URL?

后端 未结 5 1943
逝去的感伤
逝去的感伤 2020-11-28 06:21

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:

相关标签:
5条回答
  • 2020-11-28 07:01

    1) local simplest methods

    <?php
    echo readfile("http://example.com/");   //needs "Allow_url_include" enabled
    //OR
    echo include("http://example.com/");    //needs "Allow_url_include" enabled
    //OR
    echo file_get_contents("http://example.com/");
    //OR
    echo stream_get_contents(fopen('http://example.com/', "rb")); //you may use "r" instead of "rb"  //needs "Allow_url_fopen" enabled
    ?> 
    

    2) Better Way is CURL:

    echo get_remote_data('http://example.com'); // GET request 
    echo get_remote_data('http://example.com', "var2=something&var3=blabla" ); // POST request
    

    It automatically handles FOLLOWLOCATION problem + Remote urls:
    src="./imageblabla.png" turned into:
    src="http://example.com/path/imageblabla.png"

    Code : https://github.com/tazotodua/useful-php-scripts/blob/master/get-remote-url-content-data.php

    0 讨论(0)
  • 2020-11-28 07:12

    Don't forget: to get HTTPS contents, your OPENSSL extension should be enabled in your php.ini. (how to get contents of site use HTTPS)

    0 讨论(0)
  • 2020-11-28 07:13
    $url = "https://chart.googleapis....";
    $json = file_get_contents($url);
    

    Now you can either echo the $json variable, if you just want to display the output, or you can decode it, and do something with it, like so:

    $data = json_decode($json);
    var_dump($data);
    
    0 讨论(0)
  • 2020-11-28 07:20

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

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

    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.

    0 讨论(0)
  • 2020-11-28 07:20

    Use file_get_contents in combination with json_decode and echo.

    0 讨论(0)
提交回复
热议问题