通过需要身份验证的URL访问Json数据

问题描述 投票:1回答:2

我似乎找不到更多关于如何通过PHP完全操作Json数据的教程或资源。看起来大多数事情都可以通过一些功能等轻松完成。但是我似乎无法找到如何访问受密码保护并需要进行身份验证的Json URL。

例如,我想访问像http://armchairanalysis.com/api/1.0/game/1200/conversions这样的链接,但它需要我明显拥有的身份验证。但不确定如何在代码中添加身份验证。

现在我有

$url ='http://armchairanalysis.com/api/1.0/game/1200/conversions';
$data = file_get_contents($url);
$characters = json_decode($data);

echo $characters[10]->;

该代码很简单,只是不确定身份验证部分。

任何帮助表示赞赏。谢谢

php json
2个回答
0
投票

此API需要HTTP基本身份验证才能访问。正确的方法是将file_get_contents函数包装在HTTP上下文中

$url ='http://armchairanalysis.com/api/1.0/game/1200/conversions';

// provide your username and password here
$auth = base64_encode("username:password");

// create HTTP context with basic auth
$context = stream_context_create([
    'http' => ['header' => "Authorization: Basic $auth"]
]);

// query for data
$data = file_get_contents($url, false, $context);

0
投票
$username="username";
$password="password";
$url="example.com";
$context = stream_context_create(array(
  'http' => array(
            'header'  => "Authorization: Basic " . base64_encode("$username:$password")
        )
    ));
$json = file_get_contents($url, false, $context);
print_r(json_decode($json)); 
© www.soinside.com 2019 - 2024. All rights reserved.