JSON Verilerini PHP cURL ile YAYINLAMA


132

İşte kodum

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

Ve diğer sayfada, gönderi verilerini alıyorum.

    print_r ($_POST);

Çıktı

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

Yani, kendi sunucumda bile düzgün veri alamıyorum, bu boş dizi. REST'i http://docs.shopify.com/api/customer#create adresindeki gibi json kullanarak uygulamak istiyorum


2
Sen dönüştürme eksik değil $dataiçin $data_stringkullanıyor json_encode()??? Bu kod satırını
— görmeyin

Üzgünüm buraya yazmadım ama codekoduma $ data_string = json_encode ($ data) yazdım ; codeve yorumlarda kod nasıl yazılır? yorumlarda satır sonu yazamıyorum ve bu yüzden kod nasıl yazılır?
— user1463076

Yanıtlar:


193

JSON'u yanlış bir şekilde POST'luyorsunuz - ancak doğru olsa bile, kullanarak test edemezsiniz print_r($_POST)( nedenini buradan okuyun ). Bunun yerine, ikinci sayfanızda, file_get_contents("php://input")POSTed json'u içerecek olan kullanarak gelen isteği yakalayabilirsiniz . Alınan verileri daha okunaklı bir biçimde görüntülemek için şunu deneyin:

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

Kodunuzda, Content-Type:application/jsontüm POST verilerini json olarak kodlamıyorsunuz, ancak yalnızca "müşteri" POST alanının değerini belirtiyorsunuz . Bunun yerine şuna benzer bir şey yapın:

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

Ek not: Shopify API ile doğrudan kendiniz arayüz oluşturmak yerine üçüncü taraf bir kitaplıktan yararlanabilirsiniz .


1
Hah! Verileri $ _POST yoluyla neden alamadığım konusunda mücadele ediyordum. Sorun, söylediğin gibi php: // input kullanmak zorunda olmamdı. Teşekkürler.
— YOMorales

yani POST isteği olduğunu açıkça belirtmek zorunda değilsiniz? CURLOPT_POSTFIELDS ayarlandığı için mi biliniyor?
— Srneczek

Geçen hafta bütün hafta aradığımda bu cevap neredeydi? Şimdi kendim çözmem gerektiğinden sonra bir yolunu buluyorum!
— pythonian29033

Ek not: JSON gönderir ve yanıt olarak JSON'u beklerseniz, bazı API'ler de yanıt türünü ayarlamayı gerektirir curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'Accept:application/json'));(aksi takdirde JSON gönderebilir, ancak yanıt olarak XML alabilirsiniz).
— pixelbrackets

2
günü kurtardın
— 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);

Bu kod benim için çalıştı. Deneyebilirsin...


13

değiştirmek

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

ile:

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

"Diğer sayfa" ile ne demek istediğini anlayamıyorum, umarım bu sayfadır: 'url_to_post'. Bu sayfa PHP'de yazıldıysa, yukarıda yayınladığınız JSON aşağıdaki şekilde okunacaktır:

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

Neden bunu varsayıyorsun? Verileri 'müşteri' alanına koyuyorsa, bunu bir nedenden dolayı yapıyor olmalı, değil mi?
— Okonomiyaki3000

Evet, teşekkürler, o kısmı kaçırdım. Ama o, IMO, yanlış yapıyor. Cevabımı onunla güncelleyeceğim.
— UltraInstinct

Yukarıdaki çözümlerden hiçbiri json verilerini php dosyasında almak için işe yaramaz :(
— Gohel Kiran

7

Lütfen bu kodu deneyin: -

$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

Bu örneği deneyin.

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

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

?>

1

Şöyle dene:

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

Unuttuğunuz en önemli şey verilerinizi json_encode etmekti. Ancak, bir dizi geçirerek tüm curl seçeneklerini bir kerede ayarlamak için curl_setopt_array'ı kullanmayı uygun bulabilirsiniz.


-1. API'yi buradan kontrol edin: api.shopify.com/customer.html#create . Sunucunun urlencoded-json'da değil, JSON'da beklediği gövde. Cevabımı kontrol edin array(..), `` CURLOPT_POSTFIELDS
— UltraInstinct

Evet, dediğim gibi yanlış gönderiyor. Bir array(..)CURLOPT_POSTFIELDS`e geçirmek JSON’u da urlencode edecektir.
— UltraInstinct

Her neyse, birçok kez farklı kodla denedim ama json'da yapamadım, şimdi xml'de başarılı bir şekilde yaptım.
— user1463076
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.