我想通过一个json数据作为参数cURL POST。但是,我坚持抓住它并将其保存在数据库中。通过CURL POST JSON数据并抓取它
卷曲文件:
$data = array("name" => "Hagrid", "age" => "36");
$data_string = json_encode($data);
$url = 'http://localhost/project/test_curl';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json')
);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
$result = curl_exec($ch);
//based on http://www.lornajane.net/posts/2011/posting-json-data-with-php-curl
test_curl文件:
$order_info = $_POST; // this seems to not returning anything
//SAVE TO DB... saving empty...
我错过了什么? Weew ....
作为您的教程链接提到你有内容长度参数添加为一个额外的头。我可以确保这个教程完全起作用(我在2天前使用了它)。如果这不起作用,那么curl请求的设计目标可能没有预期的行为。 – TRD 2012-01-30 10:03:13
顺便说一句,CURLOPT_POSTFIELDS需要一个关联数组来发布,像数组('data'=> $ data_string),否则它不会发布任何信息 – dievardump 2012-01-30 10:06:42
@DieVarDump这是不正确的。它接受一个字符串或一个关联数组。如果你想使用'Content-Type:application/json',它*必须*是一个字符串。最好自己创建一个字符串并传递它,因为如果传递一个数组,Content-Type将成为'multipart/form-data',并且请求体可能会比使用'应用程序/ x-WWW的形式urlencoded'。 – DaveRandom 2012-01-30 10:08:09