使用PHP使用curl获取JSON数据

时间:2016-11-09 20:49:02

标签: php curl

我正在尝试使用PHP来使用curl获取JSON数据,但是我收到错误302,并且没有返回数据。

我可以使用以下命令在命令行执行curl:

curl -X GET --header "Accept: application/json" "https://api.lootbox.eu/pc/us/Hydropotamus-1777/profile"

以下是当前无法运行的PHP脚本:

<?php
// Get cURL resource
$url = 'https://api.lootbox.eu/pc/eu/Hydropotamus-1777/profile';
$curl = curl_init($url);
echo "A";
// Set some options - we are passing in a useragent too here
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
  'Accept: application/json'
));
echo "B";

$resp = curl_exec($curl);
echo "C";
echo $resp;
// Close request to clear up some resources
curl_close($curl);
 ?>

以下是一些可能有用的环境细节:

  • Windows 10
  • PHP 5.6.24
  • Chrome浏览器

2 个答案:

答案 0 :(得分:0)

一个很好用的工具是PHP中的RESTRequest类,https://gist.github.com/therealklanni/3440166然后你可以这样做:

 <?php 
session_start();
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
include_once("RestRequest.php");
$url = 'https://api.lootbox.eu/pc/eu/Hydropotamus-1777/profile';

$getDataRequest = new RestRequest($dataurl, 'GET');
$getDataRequest->execute();
$data = json_decode($getDataRequest->responseBody);

echo(json_encode($data));
?>

答案 1 :(得分:0)

好吧,我尝试了以下内容,它对我有用,得到了回复:

    <?php
// Get cURL resource
$url = 'https://api.lootbox.eu/pc/eu/Hydropotamus-1777/profile';
//  Initiate curl
$ch = curl_init();

curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
  'Accept: application/json'
));

// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);

// Will dump a beauty json :3
var_dump(json_decode($result, true));
?>

似乎您需要禁用ssl验证。