php传递var到curl请求

时间:2016-09-24 04:54:35

标签: php curl

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

以下是我尝试的内容

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",
  ),
));

1 个答案:

答案 0 :(得分: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",
)
));