user3447238
user3447238

Reputation: 3

Displaying JSON from an API in and HTML table using PHP

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.

Upvotes: 0

Views: 5122

Answers (1)

jraede
jraede

Reputation: 6896

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>';

Upvotes: 1

Related Questions