0

im experimenting with JSON Api's with PHP. Im using a free Bitcoin price ticker api from Blockchain. Its working but to refresh the data i need to refresh the page. Would it be possible to auto-update the data without refreshing the page? This is what i got now (its working)

<?php

$json = file_get_contents('https://blockchain.info/ticker');
$data = json_decode($json,true);

$priceUSD = $data['USD']['last'];

echo $priceUSD;

Thanks in advance, have a nice day!

King regards,

L Kenselaar

Luuk Kenselaar
  • 161
  • 1
  • 7
  • Are you using ajax to hit a web service that calls this PHP code? Or are you just loading this right into an HTML php file? If HTML, you could look at doing a meta refresh: https://www.w3schools.com/tags/att_meta_http_equiv.asp OR, if using ajax with JS, you could place your ajax function inside of a function that is called by a JS interval that runs every nth seconds to go and get the new price, etc. https://stackoverflow.com/questions/4930439/call-jquery-ajax-request-each-x-minutes – Woodrow Mar 27 '18 at 20:38
  • go with socketio – sumit Mar 27 '18 at 20:40

2 Answers2

0

In order to refresh the data in your PHP array, you'll have to run a new HTTP request against your API from within the PHP code. Without refreshing the page where your PHP renders, you would need to keep the connection open (which will only last for as long as your php.ini max_execution_time is and PHP can't edit data it has already sent, so the closest you could get is a news ticker that appends new lines at the bottom)

If all you want is a self-refreshing website, you'll have to use JavaScript (that can run infinitely and request new data from your PHP backend in regular intervals). Look for AJAX or XMLHttpRequests in general.

Mastacheata
  • 1,866
  • 2
  • 21
  • 32
0

If you must stick to PHP you might want to run an independent process in background (checkout nohup or disown on Linux/Unix).

Your script would do something like:

<?php

while(true){
    try {
        $json = file_get_contents('https://blockchain.info/ticker');
        $data = json_decode($json,true);

        $priceUSD = $data['USD']['last'];

        // Do the internal handling
        // update your database, etc
    }
    catch (Exception $e) {
        echo 'Error: ' .  $e->getMessage() . "\n";
    }

    // wait for 5 seconds
    sleep(5);
}

Keep in mind that PHP code runs in a blocking thread and this means that this process has to run aside of your web server.

However, if you wanted to both tasks at the same time (fetching and serving requests), you would have to consider alternatives like NodeJS.

brickpop
  • 2,754
  • 1
  • 13
  • 12