给定具有json格式数据的API,如何在HTML表格中显示数据?

时间:2017-07-10 22:33:15

标签: php html json postman dhis-2

到目前为止,我有这个PHP cURL代码:

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://play.dhis2.org/release1/api/25/analytics.json?dimension=dx%3AYtbsuPPo010%3Bl6byfWFUGaP%3Bs46m5MS0hxu&dimension=pe%3ALAST_12_MONTHS&filter=ou%3AImspTQPwCqd&displayProperty=NAME&skipMeta=true",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "authorization: Basic YWRtaW46ZGlzdHJpY3Q=",
    "cache-control: no-cache",
    "postman-token: c7fc6164-194a-24ea-ccea-9f6bdbcd66f5"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

到目前为止,我已尝试(未成功):

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  $data = json_decode($response, true);

  $immunization = $data["rows"];

  foreach ($immunizations as $immunization) {
    echo '<tr>';

     echo '<td>' . $immunization['name'] . '</td>';
     echo '<td>' . $immunization['date'] . '</td>';
     echo '<td>' . $immunization['type'] . '</td>';

    echo '</tr>';
 }
}

有人帮助我遍历JSON并将数据放在我的桌子上的行中。

  

API LINK

在邮递员上,使用Basic Auth,用户名:admin,密码:district 提前谢谢!

1 个答案:

答案 0 :(得分:1)

首先,你有

$immunization = $data["rows"];

foreach ($immunizations as $immunization) {

您应该将初始$immunization复数为$immunizations才能生效。所以你得到了

$immunizations = $data["rows"];

foreach ($immunizations as $immunization) {

其次,查看返回的数据,他们没有name, date, type个密钥。他们只是拥有那样的价值观。所以将循环更新为

foreach ($immunizations as $immunization) {
   echo '<tr>';

   echo '<td>' . $immunization[0] . '</td>';
   echo '<td>' . $immunization[1] . '</td>';
   echo '<td>' . $immunization[2] . '</td>';

   echo '</tr>';

}