如何使用PHP从Rapid API获取JSON数据

时间:2020-03-24 16:49:12

标签: php arrays json api

我尝试从API获取JSON数据,但是没有运气,有关此事的任何帮助出了什么问题。这是我的代码。

...
body Center(
  child: ClipPath(
    clipper: ButtonClipper(),
    child: Container(
      color: Colors.blue,
      child: RawMaterialButton(
        onPressed: () {},
        child: Container(
          height: 50,
          width: 150,
          child: Center(
            child: Text('+', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 36)),
          ),
        ),
      ),
    ),
  ),
),
...

class ButtonClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    final path = Path();
    path.moveTo(0, 0);
    path.cubicTo(size.width / 2, 0, size.width / 2, size.height, 0, size.height);
    path.cubicTo(size.width, size.height, size.width, 0, 0, 0);
    path.close();
    return path;
  }

  @override
  bool shouldReclip(ButtonClipper oldClipper) => false;
}

1 个答案:

答案 0 :(得分:1)

您正在访问$response,就好像它是一个数组一样,但不是,它是JSON。您需要先json_decode($response)

<?php

$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => "https://coronavirus-monitor.p.rapidapi.com/coronavirus/latest_stat_by_country.php?country=pakistan",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "x-rapidapi-host: coronavirus-monitor.p.rapidapi.com",
    "x-rapidapi-key: d1a16d6185msh28b0a37babf5f15p141020jsn35571bfb92c9"),
));
$response = curl_exec($curl);

$err = curl_error($curl);
curl_close($curl);
if ($err) {
    echo "cURL Error #:" . $err;
} else {
    // Changes made here:
    $data = json_decode($response);
    echo $data->latest_stat_by_country[0]->country_name . "</br>";
    echo $data->latest_stat_by_country[0]->total_cases . "</br>";
    echo $data->latest_stat_by_country[0]->new_cases . "</br>";
    echo $data->latest_stat_by_country[0]->active_cases . "</br>";
}
相关问题