【问题标题】:Put API data into a table using php使用 php 将 API 数据放入表中
【发布时间】:2016-04-07 17:38:58
【问题描述】:

我正在使用 wordpress 的插入 PHP 插件将 API 数据导入我的页面。 所以我会将最后一行的“”替换为“[/insert_php]”。

我的代码

[insert_php]
$url =  'https://www.eobot.com/api.aspx?idspeed=285967&json=true';

$args = array (
    'method' => 'GET'
);

$response = wp_remote_request($url, $args);

$body = wp_remote_retrieve_body($response);
print_r($body);
[/insert_php]

返回

MiningSHA-256:0.00000000;MiningScrypt:0.00000000;CloudSHA-256:12.72592330;Cloud2SHA-256:0.01894240;CloudScrypt:0.00000000;

我已经搜索过了,也许我没有使用正确的术语,并且找不到我的解决方案或答案。我觉得它应该比现在容易得多。我觉得我应该能够从正文中获取数组并给每个自己的变量,然后使用这些变量用 PHP 构建一个表。我哪里错了?我是否应该先将其存储在服务器上的 php 文件中,然后创建一个表,然后使用 insert php 函数以这种方式构建表?

【问题讨论】:

  • 您正在尝试访问Private API 和Private API 所需的帐户。查看此链接了解更多信息:eobot.com/developers
  • 这是我的私人账户,你可以看到它有我的用户 ID

标签: php wordpress http-get


【解决方案1】:

我已经检查了代码,它正在执行您编写的程序。请检查您使用的 API URL 是否正确,一旦您使用正确的 API URL,请使用 json_decode 函数解码返回的 json 数据 API,并在您将正确的数据转换为数组后添加,您可以创建表。

例如:

<?php
$body = wp_remote_retrieve_body($response);
$table_data = json_decode($body);
$html = array();
if(!empty($table_data)){
  $html[] = '<table>';
  foreach($table_data as $rows){
    $html[] = '<tr>';
    foreach($row as $column){
      $html[] = '<td>'. $column . '</td>';
    }
    $html[] = '</tr>';
  }
  $html ='</table>';
}
$html = implode("\n", $html);
echo $html;
?>

PS:此代码仅为示例,请自行调整数据。

【讨论】:

  • 我想这是我不知道如何问的问题是json解码部分。这是来自该站点的信息 - 简单、RESTful API - 支持 GET 和 POST - 快速、免费、无限制使用 - 通过添加 &json=true 将 JSON 添加到任何 API 请求,所以我的问题应该是如何将 json 信息放入表中?
  • @ka5050ro 好吧,这很简单,但答案取决于返回数据的内容以及您需要显示表格的数据。一旦你解码了数据,它就是一个简单的 PHP 数组,你可以迭代它来创建 HTML 表。我正在修改表格以根据可用的场景和信息编写通用答案。
【解决方案2】:

我已经尝试过你的代码,它在本地机器上对我来说工作正常,我认为你只需要输入 json_decode 以获得正确的格式。

[insert_php]
$url =  'https://www.eobot.com/api.aspx?idspeed=285967&json=true';

$args = array (
    'method' => 'GET'
);

$response = wp_remote_request($url, $args);

$body = wp_remote_retrieve_body($response);
print_r($body);
echo "<pre>";
$data = json_decode($body);
print_r($data);
[/insert_php]

获取这种类型的输出。

stdClass Object
(
    [MiningSHA-256] => 0.00000000
    [MiningScrypt] => 0.00000000
    [CloudSHA-256] => 12.72656020
    [Cloud2SHA-256] => 0.01894240
    [CloudScrypt] => 0.00000000
)

请尝试上面的代码并告诉我。

【讨论】:

  • @ka5050ro 您的代码有问题。我得到了数组,就像我输入的答案一样。
  • 也许我错过了一个插件
  • @ka5050ro 你的代码是在哪里写的?
  • 它在使用wordpress中的编辑页面功能的页面中
  • 有了你显示的输出我应该可以使用这个代码stackoverflow.com/questions/26213049/…
猜你喜欢
  • 2013-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多