Intereting Posts

Как получить данные POST JSON с помощью PHP 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); 

И на другой странице я получаю данные для публикации.

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

Итак, я не получаю правильные данные даже на моем собственном сервере, это пустой массив. Я хочу реализовать REST с помощью json, как на http://docs.shopify.com/api/customer#create

Вы неправильно используете 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 , но вы не json-encoding все данные POST – только значение поля 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>"; 

Sidenote: вам может пригодиться использование сторонней библиотеки вместо непосредственного взаимодействия с Shopify API.

замещать

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

Попробуйте этот пример.

 <?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)); ?> 

Попробуйте вот так:

 $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 для установки всех параметров завивки сразу, передав массив.