Php 解析来自远程服务器的JSON数据
我想知道是否有任何方法可以在PHP中创建一个解析器,从这个站点获取值,并将它们设置为PHP代码中的变量Php 解析来自远程服务器的JSON数据,php,json,parsing,bitcoin,Php,Json,Parsing,Bitcoin,我想知道是否有任何方法可以在PHP中创建一个解析器,从这个站点获取值,并将它们设置为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 ?
我已经看过一些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
?>
您可以使用从URL获取数据并解析结果,因为您链接的站点返回一个数组,可以由php本机解析
例如:
$bitcoin = json_decode(file_get_contents("https://btc-e.com/api/2/btc_usd/ticker"), true);
在$bitcoin
变量中,您将拥有一个带有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()(其输出不是Json mime类型,但格式类似于Json)。
如果您知道数据将是json,则可以从页面中以字符串形式获取(例如使用
file\u get\u contents
函数),并使用json\u 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'];
如果您想知道-如果有解析的方法,那么-是的,是的。那么你的问题是什么?全部工作都做了吗?添加特定的问题描述它看起来像是对我的json响应当我使用此代码时,我得到此错误致命错误:无法在C:\wamp3\www\DROPBOX\DROPBOX\FTP\Test2.php中在线使用stdClass类型的对象作为数组5@JVarhol您确定已将json\u解码($dataFromPage,true)的第二个参数设置为true吗
function?这是我的代码@ProGM我已将其设置为true,我已将我的代码包含在上面,是否有其他可能导致我出错?@JVarhol check。尝试强制转换到数组或使用print\r($data);在json_解码并检查该数据的值之后,我尝试了这个方法,但由于某种原因,我得到了一个错误,我得到了这个错误致命的错误:无法在第5行的C:\wamp3\www\DROPBOX\DROPBOX\FTP\Test2.php中使用stdClass类型的对象作为数组,默认情况下json_decode
将返回一个对象,如果必须将其用作数组,则可以使用$data=json\u decode($content,true)代码>
<?
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"];
?>