【问题标题】:Trying to print a specific part from a json url [duplicate]尝试从 json url 打印特定部分 [重复]
【发布时间】:2023-03-28 12:17:01
【问题描述】:

我正在尝试使用以下脚本获取比特币的"price"。本质上,它访问 coinmarketcap api 并打印出比特币的价格。但是,我不确定此错误的含义或如何修复它


我的代码

<?php
$url = "https://api.coinmarketcap.com/v2/ticker/";

$contents = file_get_contents($url);
$decode_content = json_decode($contents);

$myprice = $decode_content->data->1->name;

echo "Price: " . $myprice;

?>

错误信息

Fatal error: Cannot use object of type stdClass as array

【问题讨论】:

    标签: php json echo file-get-contents


    【解决方案1】:

    json_decode 有一个可选参数bool $assoc

    当为 TRUE 时,返回的对象将被转换为关联对象 数组。

    ->http://php.net/manual/en/function.json-decode.php

    【讨论】:

    • 除此注释外:它会将对象作为数组返回,因此您必须像这样访问它:$decode_content['data']['1']['name']; 而不是 $decode_content-&gt;data-&gt;1-&gt;name
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-08
    • 2021-05-03
    • 2014-06-14
    • 2016-10-03
    • 1970-01-01
    • 2017-01-22
    相关资源
    最近更新 更多