JSON-和PHP-使用密码-被回答

JSON-和PHP-使用密码-被回答,php,json,Php,Json,问题:试图从受密码保护的JSON文档中提取JSON数据 我知道用户和密码是默认值。我不会泄露我的用户信息:) 编辑:我更改了代码。现在它显示了一个有或没有解决方案的工作。首先,代码获取数据。在网站上显示数据的第二个代码(HTML) 此代码从URL获取数据: <?php error_reporting(E_ALL); $url = 'https://www.mysportsfeeds.com/api/feed/pull/nhl/2017-playoff/scoreboard.jso

问题:试图从受密码保护的JSON文档中提取JSON数据

我知道用户和密码是默认值。我不会泄露我的用户信息:)

编辑:我更改了代码。现在它显示了一个有或没有解决方案的工作。首先,代码获取数据。在网站上显示数据的第二个代码(HTML)

此代码从URL获取数据:

    <?php
error_reporting(E_ALL);

$url = 'https://www.mysportsfeeds.com/api/feed/pull/nhl/2017-playoff/scoreboard.json?fordate=20170416';

$username = 'username';
$password = 'password';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
//curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
//curl_setopt($ch, CURLOPT_REFERER, $url);


curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_UNRESTRICTED_AUTH, 1);

$result = curl_exec($ch);
$info = curl_getinfo($ch);
$nhl=json_decode($result,true);
curl_close($ch);
?>

第二个代码以HTML格式显示数据:

在索引站点中使用“
”将第一个代码放入另一个文件中,如sports-json.php

<?php foreach ($nhl['scoreboard']['gameScore'] as $game) {
         echo $game['game']['awayTeam']['Name'] . $game['awayScore'] . ' to '  . $game['game']['homeTeam']['Name'] . $game['homeScore'] . "\n";
    }


表代码的结果:

这应该与解析XML(一旦它是数组)的过程相同。下面是一个获得分数和团队的示例

$json=json_decode($da_json,true);
foreach ($json['scoreboard']['gameScore'] as $game) {
     echo $game['game']['awayTeam']['Name'] . $game['awayScore'] . ' to '  . $game['game']['homeTeam']['Name'] . $game['homeScore'] . "\n";
}
演示:


您可以
打印
var\u dump
游戏
$game
以查看可用的索引。如果您需要json对象更高层次的信息,请在
foreach
中修改
$json['scoreboard']['gameScore']

echo$resp
回波旋度错误($ch)是否检查了卷曲错误?或者从api调用获取数据?Cutsey评论说我的代码不正确,但我知道我的代码是错误的。我只是想把它弄对,希望知道json的人能帮我。根据@chris85这样的评论,你可以这样做,你也可以向我们展示json格式的响应,所以我们可以帮助你输出
$json
是不是像你之前发布的那样?在
curl\u close($ch)之后添加
变量转储($result)。回答是什么?@Nancy不,问题是您没有使用正确的用户名/密码,因此无法返回JSON。请参阅HTTP Status 401-错误凭据。同样,curl的响应是什么?问题是,您无法返回JSON。
$json=json_decode($da_json,true);
foreach ($json['scoreboard']['gameScore'] as $game) {
     echo $game['game']['awayTeam']['Name'] . $game['awayScore'] . ' to '  . $game['game']['homeTeam']['Name'] . $game['homeScore'] . "\n";
}