php传递var到curl请求

问题描述 投票:1回答:1

卷毛问题我有点问题。它根本不会采取$变量..请协助。卷曲请求的其余部分是正确的,我已设法隔离它

这是我尝试过的

CURLOPT_POSTFIELDS => "{\"msisdn\":$msisdn, \"transactionId\": $_id, \"transactionAmount\": $amount}",

$payload = json_encode(array("msisdn"=> $s_msisdn,"transactionId"=>$_id, "transactionAmount"=>$_amount));
...
 CURLOPT_POSTFIELDS => $payload,

编辑:完整的请求

$curl = curl_init();
  curl_setopt_array($curl, array(
  CURLOPT_PORT => "5001",
  CURLOPT_URL => "http://123.123.23.11:5001/demo",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{\"msisdn\":"'.$_msisdn.'", \"transactionId\": "'.$_id.'", \"transactionAmount\": "'.$_amount.'"}",  
CURLOPT_HTTPHEADER => array(
    "authorization: Basic abcdefgh",
    "content-type: application/json",
  ),
));
php curl
1个回答
2
投票

这是你可以使用的。您的JSON字符串没有得到正确的引用。我个人觉得使用数组然后json_encode更容易,它省去了担心转义变量。

$data = array (
    "msisdn" => $_msisdn,
    "transactionId" => $_id,
    "transactionAmount" => $_amount,
);
$jsonData = json_encode($data);
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_PORT => "5001",
    CURLOPT_URL => "http://123.123.23.11:5001/demo",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => $jsonData,
CURLOPT_HTTPHEADER => array(
    "authorization: Basic abcdefgh",
    "content-type: application/json",
),
));

通过修复JSON,这更接近您的代码。

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_PORT => "5001",
    CURLOPT_URL => "http://123.123.23.11:5001/demo",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => "{\"msisdn\": \"{$_msisdn}\", \"transactionId\": \"{$_id}\", \"transactionAmount\": \"{$_amount}\"}",
CURLOPT_HTTPHEADER => array(
    "authorization: Basic abcdefgh",
    "content-type: application/json",
)
));
© www.soinside.com 2019 - 2024. All rights reserved.