Reputation: 626
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.
Upvotes: 4
Views: 20118
Reputation: 6361
<?
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"];
?>
Upvotes: 2
Reputation: 5847
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'];
Upvotes: 2
Reputation: 7108
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)
}
}
Upvotes: 4
Reputation: 46910
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
?>
Upvotes: 13