从api获取数据,并以html格式显示

时间:2017-03-26 20:39:28

标签: javascript html json

我有一个如下所示的API文件: Take a look (Image)

我想从这个api获取信息并在html页面中显示它看起来像这样 enter image description here

我搜索了论坛,但找不到任何对我有益的东西。
如果有人可以提供帮助那就太棒了!感谢。

3 个答案:

答案 0 :(得分:0)

您必须将json代码解析为php中的数组:

$array = json_decode($json_data,true);

然后你可以像这样打印出来:

echo $array["bonusValues"];

这是第一级密钥。如果您有二级密钥,则必须使用以下内容:

echo $array["first"]["second"];

如果你在json中有一个数组:

echo $array["first"][0]["item_name"];

因此中间的0表示元素的增量值。

要从网址获取数据,您可以使用file_get_contents函数:

$json_data = file_get_contents("http://www.your-url.com/");

答案 1 :(得分:0)

首先,你应该下载html文件。我建议使用CURL。 接下来将数据从json解码到php数组

$array = json_decode($data, true);

使用CURL

url_setopt_array($ch, array(
     CURLOPT_RETURNTRANSFER => true,
     CURLOPT_CUSTOMREQUEST => "POST",
     CURLOPT_URL => "url",
     CURLOPT_POSTFIELDS => http_build_query(array(
     "POST FIELD" => $value,
     ))
    ));
$data = curl_exec($ch);

然后对$ array元素使用echo函数

答案 2 :(得分:0)

您可以使用jQuery $。ajax 和JSON.stringify在浏览器中以很好的方式显示JSON的内容。

像这样:

$.ajax({
   type: 'POST',
   url: '/my/api/endpoint',
   data: 'var1=value&var2=value2',
   success: function(response) {
      var data = JSON.parse(response);
      var mydata1 = data.lastTransactions;

      $("#myHtmlBox").html(JSON.stringify(obj, null, 2));
   }
});

在此处使用$ .ajax的示例:jQuery Ajax POST example with PHP

或使用PHP:

$json = json_encode(file_get_contents("http://www.myapi.com/"));
$data = $json->lastTransactions;
echo json_encode($data, JSON_PRETTY_PRINT);

还使用标签:<pre></pre>将打印出漂亮且格式化的JSON。

相关问题