目前我想从JSON API网址获取数据:
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>";
}
?>
在这里,我想获得as:
的值ANNOUNCE,NUM_SEEDERS,NUM_LEECHERS,FOUND,UPDATED。
但是我收到了这个错误:
警告:在第4行的C:\ xampp \ test.php中为foreach()提供的参数无效
答案 0 :(得分:2)
您需要添加用户代理标头
<?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>";
}
?>
答案 1 :(得分:1)
尝试以下代码并告诉我们:
<?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"].", ";
$html.=$result[$key]["NUM_SEEDERS"].", ";
$html.=$result[$key]["NUM_LEECHERS"].", ";
$html.=$result[$key]["FOUND"].", ";
$html.=$result[$key]["UPDATED"];
$html.="<br>";
}
echo $html;
?>