PHP Curl我有一个奇怪的问题。我想多次设置帖子字段选项。以下CURL代码的等效PHP代码是什么:
curl -X POST https://example.com \
-d 'contacts=my_list' \
-d 'data[]={"email":"address1@domain.com","name":"contactName1"}' \
-d 'data[]={"email":"address2@domain.com","name":"contactName2"}'
我想将数据[]作为CURLOPT_POSTFIELDS的倍数发送。我已经尝试将post field设置为
$post = "?contacts=my_list&data[]=%7B%22email%22%3A%22address1%40domain.com%22%2C%22name%22%3A%22contactName1%22%7D&data[]=%7B%22email%22%3A%22address2%40domain.com%22%2C%22name%22%3A%22contactName2%22%7D"
我们可以将curl设置CURLOPT_POSTFIELDS两次,如
$post1 = "contacts=my_list&data[]=%7B%22email%22%3A%22address1%40domain.com%22%2C%22name%22%3A%22contactName1%22%7D";
$post2 = "data[]=%7B%22email%22%3A%22address2%40domain.com%22%2C%22name%22%3A%22contactName2%22%7D";
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post1);
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post2);
curl_exec($this->ch);
答案 0 :(得分:1)
正如评论中所提到的,这是您正在寻找的代码:
<?php
$post1 = "contacts=my_list&data[]=%7B%22email%22%3A%22address1%40domain.com%22%2C%22name%22%3A%22contactName1%22%7D";
$post2 = "data[]=%7B%22email%22%3A%22address2%40domain.com%22%2C%22name%22%3A%22contactName2%22%7D";
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post1 . '&' . $post2);
curl_exec($this->ch);
?>
但最好也是最清楚的方法是将所有信息放在数组中,让http_build_query()
完成这项工作:
<?php
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, 'http://your_url_here.com');
curl_setopt($c, CURLOPT_MAXREDIRS, 10);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
$postData = array(
'contacts' => 'my_list',
'data' => array(
array('email' => 'address1@domain.com', 'name' => 'contactName1'),
array('email' => 'address2@domain.com', 'name' => 'contactName2'),
),
);
curl_setopt($c, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_exec($c);
?>
答案 1 :(得分:1)
我会说不是curl_setopt documentation:
此参数可以作为urlencoded字符串传递 'para1 = val1&amp; para2 = val2&amp; ...'或作为字段名称为键的数组 和现场数据作为价值。
做得更好curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post1."&".$post2)
或者使用干净的数组:
$post_data["contacts"] = "my_list";
$post_data["data[0]"] = "%7B%22email%22%3A%22address1%40domain.com%22%2C%22name%22%3A%22contactName1%22%7D";
$post_data["data[1]"] = "%7B%22email%22%3A%22address2%40domain.com%22%2C%22name%22%3A%22contactName2%22%7D";
curl_setopt($this->ch, CURLOPT_POSTFIELDS,$post_data);
curl_exec($this);
我不能发誓如何使用像data[]
这样的多个字段,但我认为curl会在引擎盖下进行数组操作(如果不是我看不到它如何在接收器端工作)。
编辑:在发布此内容后看到上一个答案,如果没有用,请告诉我我会删除它