[英]CURLOPT_POSTFIELDS format
我試圖將一個json字符串傳遞給curlopt_postfield。
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
我有一個工作的硬編碼示例。 但是,我無法使其動態。
$test = "84560";
$data = "{\"id\":\"" .$test. "\"}";
$data2 = "{\"id\":\"84560\"}";
curl_setopt($ch, CURLOPT_POSTFIELDS, $data2);
為什么$ data2起作用而$ data失敗? 我已經嘗試過json編碼,utf8編碼以及將引號轉義的許多變體都無濟於事。 我想念什么? 我沒有得到一個錯誤,僅僅是一個NULL響應。
這是完整的代碼。 仍然無法使其正常工作。 我嘗試了所有發現的任何其他建議。
$test = "84560";
$data = "{\"id\":\"" .$test. "\"}";
$data2 = "{\"id\":\"84560\"}";
$result2 = getJson("results.json?", $data2);
function getJson($endpoint, $postfields)
{
$URL = "https://app.mobilecause.com/api/v2/reports/". $endpoint;
$ch = curl_init();
$headers = [];
$headers[] = "Authorization: Token token=\"[token goes here]\"";
$headers[] = "Accept: application/json";
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
if (curl_errno($ch))
{
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);;
return $result;
}
您應該簡單地嘗試:
<?php
$data = array('id' => 84560);
$json = json_encode($data);
echo $json; // Will print { id: 84560 }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.