Come pubblicare i dati JSON con PHP cURL?


132

Ecco il mio codice,

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

E in un'altra pagina, sto recuperando i dati dei post.

    print_r ($_POST);

L'output è

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

Quindi, non sto ottenendo i dati corretti anche sul mio server, è un array vuoto. Voglio implementare REST utilizzando json su http://docs.shopify.com/api/customer#create


2
Non Vi manca la conversione $dataa $data_stringuso json_encode()??? Non vedere questa riga di codice ...
— shadyyx,

Mi dispiace non ho scritto qui ma nel mio codice ho scritto code$ data_string = json_encode ($ data); codee come scrivere il codice nei commenti? nei commenti non riesco a scrivere l'interruzione di riga e quindi come scrivere il codice?
— user1463076

Risposte:


193

Stai postando il json in modo errato - ma anche se fosse corretto, non saresti in grado di testare usando print_r($_POST)( leggi perché qui ). Invece, sulla tua seconda pagina, puoi prendere la richiesta in arrivo usando file_get_contents("php://input"), che conterrà il json POST . Per visualizzare i dati ricevuti in un formato più leggibile, prova questo:

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

Nel tuo codice, stai indicando Content-Type:application/json, ma non stai codificando json tutti i dati POST - solo il valore del campo POST "cliente". Invece, fai qualcosa del genere:

$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: potresti trarre vantaggio dall'utilizzare una libreria di terze parti invece di interfacciarti direttamente con l'API Shopify.


1
Hah! Stavo lottando sul perché non stavo ricevendo i dati tramite $ _POST. Il problema era che dovevo usare php: // input come hai detto tu. Grazie.
— YOMorales,

quindi non devi specificare esplicitamente che è una richiesta POST? È noto perché CURLOPT_POSTFIELDS è impostato?
— Srneczek,

dov'era questa risposta quando la cercavo tutta la settimana scorsa settimana? Ora lo trovo dopo che ho dovuto capire me stesso!
— pythonian29033,

Sidenote: se invii JSON e prevedi JSON come risposta, alcune API richiedono anche l'impostazione del tipo di risposta curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'Accept:application/json'));(altrimenti potresti inviare JSON, ma ottenere XML come risposta).
— pixelbrackets

2
hai salvato la giornata
— 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);

Questo codice ha funzionato per me. Puoi provare...


13

Sostituire

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

con:

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

Non capisco cosa intendevi per "altra pagina", spero sia la pagina su "url_to_post". Se quella pagina è scritta in PHP, il JSON che hai appena pubblicato sopra verrà letto nel modo seguente:

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

Perché dovresti assumerlo? Se sta inserendo i dati nel campo "cliente", deve farlo per un motivo, no?
— Okonomiyaki3000,

Sì, grazie, ho perso quella parte. Ma lui, IMO, sta sbagliando. Aggiornerò la mia risposta con esso.
— UltraInstinct,

Nessuna delle soluzioni precedenti funziona per ottenere dati json nel file php :(
— Gohel Kiran

7

Prova questo codice: -

$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

Prova questo esempio.

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

Il tuo codice page2.php

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

?>

1

Prova in questo modo:

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

La cosa fondamentale che hai dimenticato era di json_encode i tuoi dati. Ma potresti anche trovare conveniente usare curl_setopt_array per impostare tutte le opzioni di arricciatura contemporaneamente passando un array.


-1. Controlla l'API qui: api.shopify.com/customer.html#create . Il corpo che il server si aspetta in JSON, non urlencoded-json. Controlla la mia risposta, non c'è bisogno di usare array(..)in `CURLOPT_POSTFIELDS
— UltraInstinct

Sì, come ho detto, lo sta inviando in modo sbagliato. Passando array(..)a CURLOPT_POSTFIELDS` anche urlencode il codice JSON.
— UltraInstinct,

Ad ogni modo, ho provato molte volte con codice diverso ma non ero in grado di fare in json ora ho fatto con successo in XML.
— user1463076
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.