使用CURL使用PHP使用json的GET

时间:2012-11-04 19:26:05

标签: php json curl

我是PHP的新手,并且已经做过一些关于如何使用CURL调用json的GET函数的研究,但有些事情我没有正确完成。也许有人可以指出我正确的方向。我希望我能正确地沟通。感谢。

在我的浏览器中,当我键入: https://myWebSite.com/api/v1/people/26.json? 我的浏览器返回ID为26的人以及与他们相关的所有字段。

我现在正在尝试在PHP文件中执行此调用。这就是我所拥有的:     

//jSON URL which should be requested
$json_url = 'https://myWebSite.com';

$username = 'myUsername';  // authentication
$password = 'myPassword';  // authentication

// jSON String for request
$json_string = '/api/v1/people/26.json';

// Initializing curl
$ch = curl_init( $json_url );

// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERPWD => $username . ":" . $password,   // authentication
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $json_string
);

// Setting curl options
curl_setopt_array( $ch, $options );

// Getting results
$result =  curl_exec($ch); // Getting jSON result string
print $result;

?>

1 个答案:

答案 0 :(得分:0)

尝试将此添加到您的选项列表中:

CURLOPT_CUSTOMREQUEST => 'POST'

编辑:重新阅读OP之后,似乎对请求的内容存在误解。如果它是对URL的GET请求,则它更可能是这样的:

$json_string = '/api/v1/people/26.json';
$json_url = "https://myWebSite.com{$json_string}";

$username = 'myUsername';  // authentication
$password = 'myPassword';  // authentication

// Initializing curl
$ch = curl_init( $json_url );

// Configuring curl options
$options = array(
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_USERPWD => $username . ":" . $password,   // authentication
);