Parsing JSON data from a remote server

2019-04-09 22:41发布

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.

4条回答
Bombasti
2楼-- · 2019-04-09 22:53

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
?>
查看更多
3楼-- · 2019-04-09 22:59
<?
function GetJsonFeed($json_url)
{
$feed = file_get_contents($json_url);
return json_decode($feed, true);
}
$LTC_USD = GetJsonFeed("https://btc-e.com/api/2/ltc_usd/ticker");
$LTC_USD_HIGH = $LTC_USD["ticker"]["last"];

$BTC_USD = GetJsonFeed("https://btc-e.com/api/2/btc_usd/ticker");
$BTC_USD_HIGH = $BTC_USD["ticker"]["last"];
?>
查看更多
倾城 Initia
4楼-- · 2019-04-09 23:14

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'];
查看更多
虎瘦雄心在
5楼-- · 2019-04-09 23:15

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)
  }
}
查看更多
登录 后发表回答