"First name", "last_name" => "l-6ren">
gpt4 book ai didi

php - 如何使用 PHP cURL 发布 JSON 数据?

转载 作者:IT老高 更新时间:2023-10-28 11:48:50 25 4
gpt4 key购买 nike

这是我的代码,

$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 OK
Date: Mon, 18 Jun 2012 07:58:11 GMT
Server: Apache
X-Powered-By: PHP/5.3.6
Vary: Accept-Encoding
Connection: close
Content-Type: text/html

Array ( )

所以,即使在我自己的服务器上,我也没有得到正确的数据,它是空数组。我想使用 json 实现 REST,如 http://docs.shopify.com/api/customer#create

最佳答案

您错误地发布了 json - 但即使它是正确的,您也无法使用 print_r($_POST) ( read why here ) 进行测试。相反,在您的第二页上,您可以使用 file_get_contents("php://input") 获取传入请求,其中将包含 POST 的 json。要以更易读的格式查看接收到的数据,试试这个:

echo '<pre>'.print_r(json_decode(file_get_contents("php://input")),1).'</pre>';

在您的代码中,您表示的是 Content-Type:application/json,但您并未对所有 POST 数据进行 json 编码——只有“客户”POST 字段的值。相反,请执行以下操作:

$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>";

旁注:您可能会受益于使用 a third-party library而不是自己直接与 Shopify API 交互。

关于php - 如何使用 PHP cURL 发布 JSON 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11079135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com