PHP使用访问令牌从API获取JSON数据

时间:2017-07-25 03:13:49

标签: php json

我尝试编写代码来从API中获取JSON数据

<?php
$url = "http://api.jakarta.go.id/v1/kota/?format=json";
$ch = curl_init();
$accesstoken = "my_token";
$headr = array();
$headr[] = 'Content-length: 0';
$headr[] = 'Content-type: application/json';
$headr[] = 'Authorization: OAuth '.$accesstoken;

curl_setopt($ch, CURLOPT_HTTPHEADER,$headr);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HTTPGET, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result=curl_exec($ch);

curl_close($ch);

var_dump(json_decode($result, true));
?>

但不工作,我得到NULL数据。请帮帮我:)。

1 个答案:

答案 0 :(得分:0)

尝试一下,它对我有用。

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://api.jakarta.go.id/v1/kota');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Authorization:my_token'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>