Я пытаюсь передать переменную php в скрипт php curl, но я боюсь.
Любые мысли были бы оценены.
$thestring = "foobar";
$data = '{"last":"$thestring"}'; //this will not work
$data = '{"last":$thestring}'; //this will not work
$data = '{"last":"foobar"}'; //this does work
$url = "https://myjson.com.json"; //not my real url
$headers = array('Content-Type: application/json');
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
echo $response;
Попробуй это:
$data = '{"last":"'.$thestring.'"}';
Вы должны конкатенировать строку $data
правильно. Одиночные кавычки '
не обрабатываются PHP.
Ответ Tino решает вашу проблему, указав, что переменные php внутри одинарных кавычек не интерпретируются.
Вы также можете использовать json_encode()
вместо того, чтобы самостоятельно создавать объект.
$thestring = "foobar"; $data = json_encode (array ( "last" => $thestring ));
Или
$thestring = "foobar"; $data = array(); $data["last"] = $thestring; $data = json_encode($data);
Вы поняли эту идею.