llw
llw

Reputation: 201

How to use an API to generate a table?

There's a game I'm interested in making a widget-type table for on my website. They have a public API for "invasions", located here

I'm looking to generate a table using that information they provide. There are number of websites that already use this API and generate a table with the info, such as this website

I know how to make tables that are generated with MySQL data.

However, I've never made a table that is generated with data from an API.

Can someone get me started?

Upvotes: 1

Views: 92

Answers (2)

kenorb
kenorb

Reputation: 166737

Here is example how to use PHP DOM to create a dynamic table:

$dom = new DOMdocument();
$table = $dom->createElement('table'); // or use: $dom->loadHTML($existing_html);

// Create field values. 
$col1 = clone $col2 = clone $col3 = clone $col4 = clone $col5 = $dom->createDocumentFragment();
$col1->appendXML('<img src="some/image/example.png" />');
$col2->appendXML('<div>example of html within row</div>);
$col3->appendXML('<div>another row</div>');
$col4->appendXML('<div>and another</div>');
$col5->appendXML('<div>last column</div>');
// Note: You can use createElement, instead of appendXML if you don't want to use html inside the columns. 

// Create columns and append content.
$td1 = $dom->createElement('td'); // col1
$td1->appendChild($col1);
$td2 = $dom->createElement('td'); // col2
$td2->appendChild($col2);
$td3 = $dom->createElement('td'); // col3
$td3->appendChild($col3);
$td4 = $dom->createElement('td'); // col4
$td4->appendChild($col4);
$td5 = $dom->createElement('td'); // col5
$td5->appendChild($col5);

// Create row and append columns.
$tr = $dom->createElement('tr');
$tr->appendChild($td1)->setAttribute('class', 'some classes');
$tr->appendChild($td2)->setAttribute('class', 'some classes');
$tr->appendChild($td3)->setAttribute('class', 'some classes');
$tr->appendChild($td4)->setAttribute('class', 'some classes');
$tr->appendChild($td5)->setAttribute('class', 'some classes');

// Append row to table, and table to root document.
$table->appendChild($tr);
$dom->appendChild($table);
$output = $dom->saveHTML();
echo $output; 

Upvotes: 0

Darren
Darren

Reputation: 13128

Something like this will work. It is up to you to set it up and style it/ structure it as you require it.

    $url = "https://www.toontownrewritten.com/api/invasions";
    $data = json_decode(file_get_contents($url));

    print "<table>";
    foreach ($data->invasions as $title => $inv) {
        print "<tr>";

        print "<td>{$title}</td><td>{$inv->progress}</td><td>{$inv->asOf}</td>";

        print "</tr>";
    }
    print "</table>";

You could alternatively use something like curl to run a http request to fetch the data. It is entirely up to you as to how you implement this.

Upvotes: 1

Related Questions