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

2022-08-30 06:21:15

这是我的代码,

$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


答案 1

你错误地POSTING了json - 但即使它是正确的,你也无法测试使用(阅读为什么在这里)。相反,在第二页上,您可以使用file_get_contents(“php://input”)来捕获传入请求,该file_get_contents将包含POSTed json。要以更具可读性的格式查看接收到的数据,请尝试以下操作:print_r($_POST)

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

在您的代码中,您指示 ,但您没有对所有 POST 数据进行 json 编码 -- 只是对 “客户” POST 字段的值进行编码。相反,请执行如下操作: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>";

旁注:使用第三方库而不是直接与 Shopify API 接口,您可能会受益匪浅。


答案 2
$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_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
print_r ($result);

这段代码对我有用。你可以试试...


推荐