[英]Post a JSON object from PHP using cUrl
我已经使用php功能json_encode
创建了一个JSON对象
对象是通过以下方式制定的:
$object_array[]=array('value1' => $value1, 'value2' => $value2);
$json_output = json_encode($object_array, JSON_UNESCAPED_SLASHES);
我需要使用PHP的'cUrl'功能将$json_output
到URL。
有人可以根据上述代码提出建议吗?
使用curl发布json对象。
$data = array('value1' => $value1, 'value2' => $value2);
$data_string = json_encode($data);
$ch = curl_init('http://api.local/rest/users'); // where to post
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
urlencode()
是以编码形式发布URL的最佳方法。
$json_output = json_encode($object_array, JSON_UNESCAPED_SLASHES);
$url = 'www.example.com?url='.urlencode($json_output);
然后您将在url参数的urldecode()
之后得到数组...
$json = urldecode($_GET['url']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.