开发者

how can i post JSON object through cURL in php

开发者 https://www.devze.com 2023-01-08 11:25 出处:网络
How can I post JSON objects to a web service, through cURL in php? I have an array $data = array(\'username\'=>\'abc\',\'password\'=>\'pass\');

How can I post JSON objects to a web service, through cURL in php?

I have an array

$data = array('username'=>'abc','password'=>'pass');

The webservice which I want to call accepts JSON object, if I convert the $data to JSON with json_encode, its not working for me.

$data = json_encode($data);

curl_setopt($ch, CURLOPT_POST      ,1);
curl_setopt($ch, CURLOPT_POSTFIELDS    ,$data);

Am I doing something wrong? or I need any more parameters to set?开发者_JS百科

Thanks for help in advance.

Tanmay


Add:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 

to specify that the data is JSON. The default is application/x-www-form-urlencoded.

0

精彩评论

暂无评论...
验证码 换一张
取 消