2012-06-18 20 views
67

Oto mój kod,Jak POST dane JSON z PHP cURL?

$url = 'url_to_post'; 
    $data = array("first_name" => "First name","last_name" => "last name","email"=>"[email protected]","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); 

A na drugiej stronie, ja pobierania danych post.

print_r ($_POST); 

Wyjście jest

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

Więc ja nie dostaję odpowiednie dane nawet na własnym serwerze, to pusta tablica. Chcę, aby zaimplementować REST za pomocą JSON na http://docs.shopify.com/api/customer#create

+2

prawda brakuje konwersji '$ data' do' '$ data_string' używając json_encode()' ??? Nie widzę tej linii kodu ... – shadyyx

+0

Niestety nie napisałem tutaj, ale w moim kodzie napisałem 'code' $ data_string = json_encode ($ data); 'code' i jak pisać kod w komentarzach? w komentarzach nie mogę napisać line break i jak napisać kod? – user1463076

Odpowiedz

4

Wymień

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

z:

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

dont dostać to, co masz na myśli przez "drugiej stronie", mam nadzieję, że jest stronę pod adresem: "url_to_post". Jeśli ta strona jest napisany w PHP, JSON po prostu pisał powyżej zostanie odczytany w poniższy sposób:

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

Dlaczego miałbyś to zakładać?Jeśli umieszcza dane w polu "klienta", musi to robić z jakiegoś powodu, nie? – Okonomiyaki3000

+0

Tak, dzięki, tęskniłem za tą częścią. Ale on, IMO, robi to źle. Zaktualizuję za to moją odpowiedź. – SuperSaiyan

+0

Żadne z powyższych rozwiązań nie działa, aby uzyskać dane json w pliku php :( – user1531437

-1

Spróbuj tak:

$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 protected]","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); 

Kluczową sprawą zapomniałeś było json_encode Twoje dane. Ale możesz również wygodnie użyć curl_setopt_array, aby ustawić wszystkie opcje zwijania naraz, przekazując tablicę.

+0

-1. Sprawdź API tutaj: http://api.shopify.com/customer.html#create. Ciało, którego serwer oczekuje w JSON, nie urlencoded-json .Sprawdź moją odpowiedź, nie trzeba używać 'array (..)' w 'CURLOPT_POSTFIELDS – SuperSaiyan

+0

Rzeczywiście. Wtedy dane, które wysyła są również błędne – Okonomiyaki3000

+0

Tak, jak powiedziałem, że wysyła go źle. (...) 'do CURLOPT_POSTFIELDS' będzie urlencode JSON też – SuperSaiyan

2

Spróbuj tego przykładu.

<?php 
$url = 'http://localhost/test/page2.php'; 
    $data = array("first_name" => "First name","last_name" => "last name","email"=>"[email protected]","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; 
?> 

Kod page2.php

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

?> 
116

Piszesz JSON nieprawidłowo - ale nawet gdyby było prawidłowe, nie będzie w stanie przetestować za pomocą print_r($_POST) (read why here). Zamiast tego na drugiej stronie możesz odebrać przychodzące żądanie, używając file_get_contents("php://input"), które będzie zawierało POSTed json. Aby wyświetlić odebrane dane w formacie bardziej czytelny, spróbuj tego:

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

w kodzie, jesteś wskazując Content-Type:application/json, ale nie jesteś json kodowanie wszystkich danych POST - tylko wartość z " klient "pole POST. Zamiast zrobić coś takiego:

$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: Można skorzystać z systemu a third-party library zamiast relacje z API Shopify bezpośrednio samemu.

+0

świetnie, pracował jak urok! –

+0

Hah ! Walczyłem o to, dlaczego nie otrzymałem danych za pośrednictwem $ _POST. Problem polegał na tym, że musiałem użyć php: // input tak jak powiedziałeś. Dzięki. – YOMorales

+0

, więc nie musisz wyraźnie określać, że jest to POST? wn, ponieważ ustawiono CURLOPT_POSTFIELD? – Srneczek

0

Spróbuj tego kodu: -

$url = 'url_to_post'; 

$data = array("first_name" => "First name","last_name" => "last name","email"=>"[email protected]","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";