繁体   English   中英

将 json api curl 从 javascript 重写为 php

[英]Re-writing json api curl from javascript to php

你好,很棒的stackoverflow,我正在尝试将下面的api从javascript重写为php,以便能够使json curl但在下面显示错误

Warning: curl_setopt() expects exactly 3 parameters, 4 given in C:\xampp\htdocs\firstcare\curl.php on line 15

js卷曲

curl -X POST
 "http://my_api.com/accesstoken?grant_type=client_credentials" 
  -H "Content-Type: application/x-www-form-urlencoded" 
  -d 'client_id=$myClient_id' 
  -d 'client_secret=$myClient_secret

php curl 转换

<?php
// 0 means unlimited timeout
ini_set('max_execution_time', 0);

$data = array(
        'Content-Type' => 'application/x-www-form-urlencoded',
        'client_id' => 'myclient_id',
        'client_secret'  => 'myclient_secret'           
);
$url='http://my_api.com/accesstoken?grant_type=client_credentials';
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url,$data);
$result=curl_exec($ch);
curl_close($ch);

$json = json_decode($result, true);


echo '<pre>' . print_r($json, true) . '</pre>';

?>

谢谢

抛出错误是因为curl_setopt需要 3 个参数 - 您在这里传递了 4 个参数:

curl_setopt($ch, CURLOPT_URL,$url,$data);

我可以建议 guzzlehttp,curl 的包装器......你似乎也在 $data 中传递标头作为第四个参数删除 $data。 如果你想发送客户端 ID 作为 GET 附加 $url 与 http_build_query()

试试这些代码

<?php
// 0 means unlimited timeout
ini_set('max_execution_time', 0);

$postdata = array(
        'client_id' => 'myclient_id',
        'client_secret'  => 'myclient_secret'           
);

$header = array(
       'Content-Type' => 'application/x-www-form-urlencoded',
);

$url='http://my_api.com/accesstoken?grant_type=client_credentials';
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, true); //if you want headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);    

$result=curl_exec($ch);
curl_close($ch);

$json = json_decode($result, true);


echo '<pre>' . print_r($json, true) . '</pre>';

?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM