duanniu3385 2017-09-14 03:30
浏览 42
已采纳

从JSON获取数据

Just wondering if anyone knew what I was doing wrong here?

I am trying to get data from an API for bitcoin via php. However, I am getting no results from my php page.

$url = "https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=EUR";
    $json = file_get_contents($url);
    $json_data = json_decode($json, true);
    echo "ID: ". $json_data["id"];

However I am getting nothing show at all on the php page. If I use the code below, It works and dumps out the entire information. But, I would prefer to obtain the information separately, instead of one big dump.

$url = "https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=EUR";

$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);

var_dump(json_decode($result, true));

Anyone have any ideas why the first code block isn't working? Thanks! Very new to API and Json

  • 写回答

3条回答 默认 最新

  • duandi1636 2017-09-14 03:34
    关注

    Using cURL is much better

    Updated code (needs error checking)

    $url = "https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=EUR";
    
    $ch = curl_init();
    // Disable SSL verification
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    // Will return the response, if false it print the response
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // Set the url
    curl_setopt($ch, CURLOPT_URL,$url);
    // Execute
    $result=curl_exec($ch);
    // Closing
    curl_close($ch);
    
    $json_data = json_decode($result, true);
    
    foreach ($json_data as $item)
        echo "ID: ". $item["id"];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制