如何使用PHP curl发布JSON数据?这是我的密码 $url = 'url_to_post';
$data = array("first_name" => "First name","last_name" => "last name","email"=>"email@gmail.com","addresses"
=> array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" => "Mother","last_name"
=> "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );
$data_string = json_encode($data);
$ch=curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, array("customer"=>$data_string));
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-Type:application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
curl_close($ch);在另一页,我正在检索帖子数据。 print_r ($_POST);输出HTTP/1.1 200 OKDate: Mon, 18 Jun 2012 07:58:11 GMTServer: ApacheX-Powered-By: PHP/5.3.6Vary: Accept-EncodingConnection:
closeContent-Type: text/htmlArray ( )所以,即使在我自己的服务器上,我也没有得到正确的数据,它是空数组。我希望使用json实现REST,如http://docs.shopify.com/api/customer#create
3 回答
炎炎设计
TA贡献1808条经验 获得超4个赞
print_r($_POST)
(在这里读为什么file_get_contents("php://input")
echo '<pre>'.print_r(json_decode(file_get_contents("php://input")),1).'</pre>';
Content-Type:application/json
$ch = curl_init( $url );# Setup request to send json via POST.$payload = json_encode( array( "customer"=> $data ) );curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));# Return response instead of printing.curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );# Send request.$result = curl_exec($ch);curl_close($ch);# Print response.echo "<pre>$result</pre>";
千万里不及你
TA贡献1784条经验 获得超9个赞
$url = 'url_to_post';$data = array("first_name" => "First name","last_name" => "last name","email"=>"email@gmail.com","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" => "Mother","last_name" => "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );$postdata = json_encode($data);$ch = curl_init($url);curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);curl_setopt($ch, CURLOPT_POST, 1);curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));$result = curl_exec($ch);curl_close($ch);print_r ($result);
- 3 回答
- 0 关注
- 348 浏览
添加回答
举报
0/150
提交
取消