원격 서버에서 JSON 데이터 구문 분석
문제
이 사이트에서 값을 가져오는 PHP에서 파서를 만드는 방법이 있는지 궁금합니다. https://btc-e.com/api/2/btc_usd/ticker
PHP 코드에서 변수로 설정합니까?
나는 PHP 파서를 조금 살펴보았는데 내가 찾은 유일한 것은 웹사이트의 모든 정보를 반영하는 파서였습니다.
해결책
URL은 JSON
응답을 반환하므로
<?php
$content=file_get_contents("https://btc-e.com/api/2/btc_usd/ticker");
$data=json_decode($content);
//do whatever with $data now
?>
. 다른 팁
file_get_contents
데이터를 가져올 수 있습니다.URL 및 relinse_nofollow"> JSON 어레이, 기본적으로 PHP에 의해 파싱 될 수 있습니다.
예 :
$bitcoin = json_decode(file_get_contents("https://btc-e.com/api/2/btc_usd/ticker"), true);
.
json_decode
변수에서는 JSON 문자열의 값이있는 연관 배열이 있습니다.
결과 :
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)
}
}
. 해당 페이지의 데이터는 다음과 같습니다. 제이슨 (자바스크립트 객체 표기법) (json MIME 유형으로 출력되지 않지만 json과 같은 형식으로 출력됩니다).
만약 너라면 알다 데이터가 json이라는 것을 페이지에서 문자열로 얻을 수 있습니다(예를 들어 file_get_contents
함수)를 사용하여 연관 배열로 디코딩합니다. json_decode
기능:
<?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'];
<?
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"];
?>
. 제휴하지 않습니다 StackOverflow