user5652534
user5652534

Reputation: 31

Get JSON from a URL by PHP

I have a URL that returns a JSON object like this:

{
  "USD" : {"15m" : 7809.0, "last" : 7809.0, "buy" : 7809.85, "sell" : 7808.15, "symbol" : "$"},
  "AUD" : {"15m" : 10321.42, "last" : 10321.42, "buy" : 10322.54, "sell" : 10320.3, "symbol" : "$"},
}

URL : https://blockchain.info/ticker more info : https://blockchain.info/api/exchange_rates_api

I want to get all the data from the first line and echo it and to have it keep requesting it so its live

I have used the examples on git hub https://github.com/blockchain/api-v1-client-php/blob/master/docs/rates.md but it displays all of the data output and you have to refresh it to get it updated

please can some one point me in the right direction

ideally I would end up with something like 15 m Last Buy Sell USD ($) 7794.87 7794.87 7795.72 7794.02

I have the table and data going to the table but its echoing the whole data set rather than the first line and also I dont know how to select individual fields

How can I do it through PHP?

Upvotes: 3

Views: 22997

Answers (2)

KeyBi
KeyBi

Reputation: 140

What you need is a request php page, which will make:

1 - Get data from the site:

$data = file_get_contents('https://blockchain.info/ticker');

2 - decode the json

$decodedData = json_decode($data);

3 - Here you can access it using OOP:

var_dump($decodedData->USD);

The point here will be to retrieve data as you wish, you can mix it up with HTML in a table for example.

Then, you need a JS script, that will execute a function with setInterval, each few miliseconds. That function should make a request to a PHP page that you created earlier, get that data and change with the updated one.

Upvotes: 9

FierceScarf
FierceScarf

Reputation: 461

This Should do it:

 <?
    $seconds = 5;
    function get_live_quote($key){
        $json_string = file_get_contents('https://blockchain.info/ticker');
        $json_array = json_decode($json_string, TRUE);
        $quote = $json_array[$key];
        $keys = implode(" ",array_keys($quote));
        $values = implode(" ", array_values ($quote));
        return "$keys $values \n";
    }


    while(TRUE){
        echo get_live_quote("USD");
        sleep($seconds);
    }

Save the preceding code to a file like "quote.php". Then from your terminal just run: php quote.php

Upvotes: 1

Related Questions