【问题标题】:How to use an API to generate a table?如何使用 API 生成表格?
【发布时间】:2014-12-01 09:31:09
【问题描述】:

我有兴趣在我的网站上制作一个小部件类型的表格。 他们有一个用于“invasions”的公共 API,位于 here

我希望使用他们提供的信息生成一个表格。有很多网站已经在使用这个 API 并生成一个包含信息的表格,例如这个website

我知道如何制作使用 MySQL 数据生成的表。

但是,我从未创建过使用 API 中的数据生成的表格。

有人可以帮我入门吗?

【问题讨论】:

标签: php html api html-table


【解决方案1】:

这样的事情会奏效。您可以根据需要对其进行设置和样式/结构。

    $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>";

您也可以使用 curl 之类的东西来运行 http 请求以获取数据。这完全取决于您如何实施。

【讨论】:

  • 谢谢@Darren! print_pre($data);实际上使它不起作用,所以我删除了它,现在它工作正常。 :)。
  • if(!empty($data-&gt;invasions)) { DO THE FOREACH STUFF } 之类的东西应该可以工作。
  • Rofl,谢谢@Darren。我做了if empty($data-&gt;invasions),难怪它不起作用。哎呀!非常感谢您为我提供的所有帮助。我有最后一个问题。我稍微改变了外观,请参阅here。我添加了print "&lt;hr&gt;";。有没有办法添加print "&lt;hr&gt;"; 仅当有多个“入侵”正在进行时?谢谢!
  • if(count($data-&gt;invasions) &gt; 1) {ADD THE HR} 应该这样做:)
  • 在看到你的评论之前,我做了if ($inv[type] &gt; 1) { print "&lt;hr&gt;"; } 只是为了尝试一下,它似乎已经奏效了。不过,我会用你的。谢谢@Darren!你就是那个男人。
【解决方案2】:

这里是如何使用PHP DOM 创建动态表的示例:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-04
    • 2023-03-23
    相关资源
    最近更新 更多