从php问题的URL获取JSON对象

时间:2015-03-08 22:44:40

标签: php json

我有以下php:

<?php
$json = file_get_contents('https://www.cryptonator.com/api/full/doge-usd');
$obj = json_decode($json);
echo $obj->ticker.price;
?>

返回空白页面。然而,当我这样做时:

echo $json; 

我得到了完整的JS:

{"ticker":{"base":"DOGE","target":"USD","price":"0.00013826","volume":"14555353.11203900","change":"-0.00000236","markets":[{"market":"Bleutrade","price":"0.00014400","volume":1.49328868},{"market":"Cex.io","price":"0.00013864","volume":6236157},{"market":"Comkort","price":"0.00014990","volume":412.40655758},{"market":"Cryptsy","price":"0.00013853","volume":382887.92442395},{"market":"Exmo","price":"0.00013800","volume":7932091.2389102},{"market":"Nix-e","price":"0.00011100","volume":539.10150086},{"market":"useCryptos","price":"0.00000305","volume":3263.94735765}]},"timestamp":1425854462,"success":true,"error":""}

我只想创建一个包含'price'字段中值的变量。

感谢。

4 个答案:

答案 0 :(得分:1)

json_encode()调用返回一个嵌套对象。所以你必须解决价格属性:

echo $obj->ticker->price;

您编码的.运算符是php中的字符串连接。那不是你想要的。 php尝试连接两个字符串,第一个是stdClass类型的对象,不存在字符串转换例程。这就是你得到错误的原因。

答案 1 :(得分:1)

有办法做到这一点。

1)你可以得到像这样的值

echo $obj->ticker->price;

2)您可以将对象转换为关联数组

$obj = json_decode($json, !!'assoc');
echo $obj["ticker"]["price"];

答案 2 :(得分:0)

你想这样做:

echo $obj->ticker->price;

答案 3 :(得分:0)

这是有效的测试代码:

<?php
  $json = file_get_contents('https://www.cryptonator.com/api/full/doge-usd');
  $obj = json_decode($json,true);
  echo 'price: '.$obj['ticker']['price'];
?>

输出:价格:0.00013833