【问题标题】:Re-writing json api curl from javascript to php将 json api curl 从 javascript 重写为 php
【发布时间】:2016-09-27 00:57:02
【问题描述】:

你好,很棒的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>';

?>

谢谢

【问题讨论】:

    标签: javascript php json curl


    【解决方案1】:

    因为curl_setopt 需要 3 个参数而引发错误 - 您在此处传递了 4 个:

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

    【讨论】:

    • 如何将其设为 3 个参数并确保代码正常工作
    【解决方案2】:

    我可以建议 guzzlehttp,curll 的包装器......而且你似乎在 $data 中传递标头作为第四个参数删除 $data。如果您想以 GET 形式发送客户 ID,请在 $url 后面加上 http_build_query()

    【讨论】:

    • 那么它以什么方式不起作用,什么错误。凭证是否需要邮寄或发送
    【解决方案3】:

    试试这些代码

    <?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>';
    
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-17
      • 2017-12-03
      • 2018-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-03
      相关资源
      最近更新 更多