簡體   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