duanniu4106 2014-03-21 16:17
浏览 33
已采纳

使用PHP在API和HTML表中显示JSON

I realize there is likely something very easy I'm missing here. Also, I'm very new to php so please keep that in mind when responding :)

I am trying to display the results from an API call in an html table. Here is my code:

// construct the query with our apikey and the query we want to make
$endpoint = 'http://www.coinmine.pw/api.php?method=coinprofit';
// setup curl to make a call to the endpoint
$session = curl_init($endpoint);
// indicates that we want the response back
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// exec curl and get the data back
$data = curl_exec($session);
// remember to close the curl session once we are finished retrieveing the data
curl_close($session);
// decode the json data to make it easier to parse the php
$search_results = json_decode($data, true);
if ($search_results === NULL) die('Error parsing json');
//print_r($search_results);

echo '<table>';
foreach ($search_results as $coin) {

$name = $coin["name"];
$profit = $coin["profit"];

echo '<tr><td>' . $name . '</tr></td>';
echo '<tr><td>' . $profit . '</tr></td>';

}
echo '</table>';

All the above outputs is name profit name profit name profit but with no separate table rows.

Ideally I'd like the whole api call to be in a table, but I'm just trying to get this to display properly first so I can figure out making the whole table.

Bonus points if someone can point me in the right direction to make the table sortable by each column.

  • 写回答

1条回答 默认 最新

  • douyuan4357 2014-03-21 16:27
    关注

    You're closing your <tr> before closing the child <td>. Should be:

    echo '<tr><td>' . $name . '</td></tr>';
    echo '<tr><td>' . $profit . '</td></tr>';
    

    But it looks like you want each $coin to be its own row, in which case it should be:

    echo '<tr><td>'.$name.'</td><td>'.$profit.'</td></tr>';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失