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

use*_*076 115 php rest json curl

这是我的代码,

$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);
Run Code Online (Sandbox Code Playgroud)

在其他页面,我正在检索发布数据.

    print_r ($_POST);
Run Code Online (Sandbox Code Playgroud)

输出是

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 ( ) 
Run Code Online (Sandbox Code Playgroud)

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

Ste*_*ris 171

你正在错误地发布json - 但即使它是正确的,你也无法测试使用print_r($_POST)(在这里阅读原因).相反,在第二页上,您可以使用file_get_contents("php://input")包含POSTed json的传入请求.要以更易读的格式查看收到的数据,请尝试以下操作:

echo '<pre>'.print_r(json_decode(file_get_contents("php://input")),1).'</pre>';
Run Code Online (Sandbox Code Playgroud)

在您的代码中,您指示Content-Type:application/json,但您不是json编码所有POST数据 - 只是"customer"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>";
Run Code Online (Sandbox Code Playgroud)

旁注:您可能会受益于使用第三方库而不是直接与Shopify API进行交互.

  • 旁注:如果您发送 JSON 并期望 JSON 作为响应,那么某些 API 还需要设置响应类型 `curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'Accept:application/json') );`(否则你可以发送 JSON,但得到 XML 作为答案)。 (3认同)

小智 14

$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);
Run Code Online (Sandbox Code Playgroud)

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

  • 正确的 JSON 编码应该有一个像这样的数组 `$data = array("customer"=&gt; array("first_name" =&gt; "First name", "last_name" =&gt; "last name", ... ` (2认同)

Ult*_*nct 11

更换

curl_setopt($ch, CURLOPT_POSTFIELDS, array("customer"=>$data_string));
Run Code Online (Sandbox Code Playgroud)

有:

$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);
Run Code Online (Sandbox Code Playgroud)

我不明白你的意思是"其他页面",我希望它是在'url_to_post'的页面.如果该页面是用PHP编写的,那么上面发布的JSON将以下面的方式阅读:

$jsonStr = file_get_contents("php://input"); //read the HTTP body.
$json = json_decode($jsonStr);
Run Code Online (Sandbox Code Playgroud)


小智 9

第一的,

  1. 始终使用 CURLOPT_CAPATH 选项定义证书,

  2. 决定如何传输您发布的数据。

1 证书

默认情况下:

  • CURLOPT_SSL_VERIFYHOST == 2其中“检查通用名称是否存在,并验证它是否与提供的主机名匹配”和

  • CURLOPT_VERIFYPEER == true其中“验证对等方的证书”。

所以,你所要做的就是:

const CAINFO = SERVER_ROOT . '/registry/cacert.pem';
...
\curl_setopt($ch, CURLOPT_CAINFO, self::CAINFO);
Run Code Online (Sandbox Code Playgroud)

取自工作类,其中SERVER_ROOT是在应用程序引导期间定义的常量,例如在自定义类加载器、另一个类等中。

忘记诸如 \curl_setopt($handler, CURLOPT_SSL_VERIFYHOST, 0);或 之类的东西\curl_setopt($handler, CURLOPT_SSL_VERIFYPEER, 0);

找到这个问题中看到的cacert.pem 地方

2种开机自检模式

发布数据时实际上有2种模式:

  • 数据传输时Content-Type标头设置为multipart/form-dataor,

  • 数据是带有application/x-www-form-urlencoded编码的 urlencoded 字符串。

在第一种情况下,您传递一个数组,而在第二种情况下,您传递一个urlencoded string

multipart/form-data前任。:

$fields = array('a' => 'sth', 'b' => 'else');
$ch = \curl_init();
\curl_setopt($ch, CURLOPT_POST, 1);
\curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
Run Code Online (Sandbox Code Playgroud)

application/x-www-form-urlencoded前任。:

$fields = array('a' => 'sth', 'b' => 'else');
$ch = \curl_init();
\curl_setopt($ch, CURLOPT_POST, 1);
\curl_setopt($ch, CURLOPT_POSTFIELDS, \http_build_query($fields));
Run Code Online (Sandbox Code Playgroud)

http_build_query:

在命令行中测试它,如下所示

user@group:$ php -a
php > $fields = array('a' => 'sth', 'b' => 'else');
php > echo \http_build_query($fields);
a=sth&b=else
Run Code Online (Sandbox Code Playgroud)

POST 请求的另一端将定义适当的连接模式。


Oko*_*000 6

尝试这样:

$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);
Run Code Online (Sandbox Code Playgroud)

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


小智 6

请尝试以下代码: -

$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";
Run Code Online (Sandbox Code Playgroud)