从 JSON API 获取数据时出错


Error on getting data from a JSON API

>目前我想从 JSON API URL 获取数据:

http://bitsnoop.com/api/trackers.php?hash=3BA918BF6B648BB6BEC6AAC716F1855451016980&json=1

我尝试了以下方法:

<?php
$query = file_get_contents('http://bitsnoop.com/api/trackers.php?hash=3BA918BF6B648BB6BEC6AAC716F1855451016980&json=1');
$parsed_json = json_decode($query, true);
foreach ($parsed_json as $key => $value)
{
    echo $value['ANNOUNCE'];
    echo "<br>";
}
?>

在这里,我想获取以下值:

宣布、NUM_SEEDERS、NUM_LEECHERS、找到、更新。

但是我收到此错误:

警告:在第

4 行的 C:''xampp''test.php 中为 foreach() 提供的参数无效

您需要添加用户代理标头

<?php
 function get_json($url, $curl = true) {
    $responseString = '';
    if (!$curl) {
        $responseString = file_get_contents($url);
    } else {
        $ch = curl_init( $url );
        $options = array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => array('Content-type: application/json', 'User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36') , 
        );
        curl_setopt_array( $ch, $options );
        $responseString =  curl_exec($ch);
    }
    return $responseString;
}
$url ="http://bitsnoop.com/api/trackers.php?hash=3BA918BF6B648BB6BEC6AAC716F1855451016980&json=1";
$query = get_json($url);
$parsed_json = json_decode($query, true);
foreach ($parsed_json as $key => $value)
{
    echo $value['ANNOUNCE'];
    echo "<br>";
}
?>

尝试以下代码并让我知道:

<?php
$loginUrl = 'http://bitsnoop.com/api/trackers.php?hash=3BA918BF6B648BB6BEC6AAC716F1855451016980&json=1';
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$loginUrl);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
$result=curl_exec($ch);
curl_close($ch);
$result=json_decode($result,true);

$html="ANNOUNCE, NUM_SEEDERS, NUM_LEECHERS, FOUND, UPDATED.";
foreach($result as $key=>$value)
{
    $html.=$result[$key]["ANNOUNCE"].",&nbsp;&nbsp;";
    $html.=$result[$key]["NUM_SEEDERS"].",&nbsp;&nbsp;";
    $html.=$result[$key]["NUM_LEECHERS"].",&nbsp;&nbsp;";
    $html.=$result[$key]["FOUND"].",&nbsp;&nbsp;";
    $html.=$result[$key]["UPDATED"];
    $html.="<br>";
}
echo $html;
?>