Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON data from a remote server

I was wondering if there was any way to make a Parser in PHP in which gets the values from this site https://btc-e.com/api/2/btc_usd/ticker and sets them as variables in php code?

I have looked at php parsers a bit and the only thing I found was parsers that echo all the information on a website.

like image 801
JVarhol Avatar asked Jan 09 '14 13:01

JVarhol


3 Answers

Since that URL returns a JSON response:

<?php

$content=file_get_contents("https://btc-e.com/api/2/btc_usd/ticker");
$data=json_decode($content);
//do whatever with $data now
?>
like image 170
Hanky Panky Avatar answered Sep 30 '22 15:09

Hanky Panky


You can use file_get_contents to get the data from the URL and json_decode to parse the result, because the site you have linked is returning a JSON array, that can be parsed by php natively.

Example:

$bitcoin = json_decode(file_get_contents("https://btc-e.com/api/2/btc_usd/ticker"), true);

In the $bitcoin variable you will have an associative array with the values of the JSON string.

Result:

array(1) {
  ["ticker"]=>
  array(10) {
    ["high"]=>
    float(844.90002)
    ["low"]=>
    int(780)
    ["avg"]=>
    float(812.45001)
    ["vol"]=>
    float(13197445.40653)
    ["vol_cur"]=>
    float(16187.2271)
    ["last"]=>
    float(817.601)
    ["buy"]=>
    float(817.951)
    ["sell"]=>
    float(817.94)
    ["updated"]=>
    int(1389273192)
    ["server_time"]=>
    int(1389273194)
  }
}
like image 31
ProGM Avatar answered Sep 30 '22 17:09

ProGM


The data on that page is called Json (JavaScript Object Notation) (its not output as json mime type, but it is formated like json).
If you know that the data will be json, you can aquire it as a string from the page (using for example the file_get_contents function) and decode it to an associative array with the json_decode function:

<?php
$dataFromPage = file_get_contents($url);
$data = json_decode($dataFromPage, true);
// Then just access the data from the assoc array like:
echo $data['ticker']['high'];
// or store it as you wish:
$tickerHigh = $data['ticker']['high'];
like image 34
Jite Avatar answered Sep 30 '22 16:09

Jite