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


132

这是我的代码,

$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 ( ) 

因此,即使在我自己的服务器上,我也无法获得正确的数据,它是空数组。我想在http://docs.shopify.com/api/customer#create中使用json实现REST


2
您不是想转换$data$data_string使用json_encode()??? 吗?看不到这行代码...
shadyyx 2012年

抱歉我没有在这里写,但是在我的代码中我写了code$ data_string = json_encode($ data); code以及如何在注释中编写代码?在注释中,我无法写换行符,那么如何编写代码?
user1463076 2012年

Answers:


193

您错误地发布了json-但即使它是正确的,您也无法使用进行测试print_r($_POST)在此处阅读原因)。相反,在第二页上,您可以使用file_get_contents("php://input")捕获传入的请求,其中将包含POSTed 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>";

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


1
哈哈!我在为为什么我没有通过$ _POST接收数据而苦苦挣扎。问题是我必须像您说的那样使用php:// input。谢谢。
YOMorales

所以您不必明确指定它是POST请求?是否知道因为设置了CURLOPT_POSTFIELDS?
斯奈切克2015年

上周我一直在寻找答案时,这个答案在哪里?现在,在不得不弄清楚自己之后,我发现了它!
pythonian29033 '16

旁注:如果您发送JSON并希望将JSON作为响应,则某些API也需要设置响应类型curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'Accept:application/json'));(否则,您可以发送JSON,但获取XML作为答案)。
pixelbrackets

2
您挽救了一天
Nisal Edu

29
$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);

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


13

更换

curl_setopt($ch, CURLOPT_POSTFIELDS, array("customer"=>$data_string));

与:

$data_string = json_encode(array("customer"=>$data));
//Send blindly the json-encoded string.
//The server, IMO, expects the body of the HTTP request to be in JSON
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);

我没有得到“其他页面”的含义,我希望它是位于“ url_to_post”的页面。如果该页面是用PHP编写的,那么上面刚刚发布的JSON将以以下方式读取:

$jsonStr = file_get_contents("php://input"); //read the HTTP body.
$json = json_decode($jsonStr);

你为什么要假设呢?如果他将数据放在“客户”字段中,那一定是有原因的,不是吗?
Okonomiyaki3000 2012年

是的,谢谢,我错过了那部分。但是他,IMO,做错了。我将用它更新我的答案。
UltraInstinct 2012年

上述解决方案均无法在php文件中获取json数据:(
Gohel Kiran 2012年

7

请尝试以下代码:-

$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(array("customer" =>$data));

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);

curl_close($ch);

echo "$result";

3

试试这个例子。

<?php 
 $url = 'http://localhost/test/page2.php';
    $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" ) );
    $ch=curl_init($url);
    $data_string = urlencode(json_encode($data));
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, array("customer"=>$data_string));


    $result = curl_exec($ch);
    curl_close($ch);

    echo $result;
?>

您的page2.php代码

<?php
$datastring = $_POST['customer'];
$data = json_decode( urldecode( $datastring));

?>

1

尝试这样:

$url = 'url_to_post';
// this is only part of the data you need to sen
$customer_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" ) );
// As per your API, the customer data should be structured this way
$data = array("customer" => $customer_data);
// And then encoded as a json string
$data_string = json_encode($data);
$ch=curl_init($url);

curl_setopt_array($ch, array(
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $data_string,
    CURLOPT_HEADER => true,
    CURLOPT_HTTPHEADER => array('Content-Type:application/json', 'Content-Length: ' . strlen($data_string)))
));

$result = curl_exec($ch);
curl_close($ch);

您忘记的关键是对数据进行json_encode。但是您也可能会发现使用curl_setopt_array通过传递数组一次设置所有curl选项很方便。


-1。在此处检查API:api.shopify.com/customer.html#create。服务器期望的主体为JSON,而不是urlencoded-json。检查我的回答,无需array(..)在`CURLOPT_POSTFIELDS中使用
UltraInstinct 2012年

是的,正如我说的,他发错了。传递array(..)给CURLOPT_POSTFIELDS`也会对JSON进行urlencode。
UltraInstinct 2012年

无论如何,我用不同的代码尝试了很多次,但是我现在无法在json中做,而在xml中却成功了。
user1463076'6
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.