2013-09-25 25 views
51

Bu soruyu göndermeden önce çok fazla etrafa baktım, bu yüzden başka bir gönderiyse özür dilerim ve bu soruyu doğru biçimlendirmezsem özür dilerim.Okuma JSON POST kullanarak PHP

Oluşturduğum ve post değerlerini alması ve JSON kodlu bir dizi döndürmesi gereken gerçekten basit bir web hizmetim var. Her şey bana söylenene kadar iyi çalıştı, form verisini içerik türü bir uygulama/json ile göndermem gerekecek. O zamandan beri web hizmetinden herhangi bir değer döndüremiyorum ve kesinlikle kendi posta değerlerini filtrelemeyle ilgili bir şey.

<?php 

header('Content-type: application/json'); 

/* connect to the db */ 
$link = mysql_connect('localhost','root','root') or die('Cannot connect to the DB'); 
mysql_select_db('webservice',$link) or die('Cannot select the DB'); 

if(isset($_POST['action']) && $_POST['action'] == 'login') { 
    $statusCode = array('statusCode'=>1, 'statusDescription'=>'Login Process - Fail'); 
    $posts[] = array('status'=>$statusCode); 
    header('Content-type: application/json'); 
    echo json_encode($posts); 

    /* disconnect from the db */ 
} 
@mysql_close($link); 

?> 
- Bu (I fonksiyonların bazılarını çalmıştır) olan webservice günü

$curl = curl_init(); 
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");                  
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);                 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);                  
curl_setopt($curl, CURLOPT_HTTPHEADER, array(                   
    'Content-Type: application/json',                     
    'Content-Length: ' . strlen($data))                  
); 
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/'); // Set the url path we want to call 
$result = curl_exec($curl); 

//see the results 
$json=json_decode($result,true); 
curl_close($curl); 
print_r($json); 

-

Temelde benim yerel kurulumunda ben aşağıdakileri yapar bir test sayfası oluşturduk

Temelde bunun getirilmedim $ _POST değerlere bağlı olduğunu biliyoruz ama ben $ yerine _POST koymak için gerekenleri bulamıyorum. Ben json_decode ($ _ POST), file_get_contents ("php: // input") denenmiş ve diğer yollarla bir dizi ama karanlık biraz çekiyordum.

Herhangi bir yardım büyük memnuniyetle karşılanacaktır.

sayesinde Steve

o

güncellenmiş boş olsa bile Michael yardım, ben yazı yankı zaman ileriye şimdi en azından bir repsonse var kesin bir adımdı

Teşekkür .... CURL -

$curl = curl_init(); 
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 
    curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/'); 
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); 
veri yayınlanır sayfadaki

güncellenmiş php -

$inputJSON = file_get_contents('php://input'); 
$input= json_decode($inputJSON, TRUE); //convert JSON into array 

print_r(json_encode($input)); 

En azından ben boş bir sayfa dönüyor önce wheras bir yanıt görüyorum dediğim gibi

+0

Başarısızlığın ne olduğundan emin olmadığından emin olun, ancak IMHO, ilk adım, içinde ne olduğunu görmek için $ _POST içeriğinin üstünden dışarı çıkar. Eğer veriler varsa, onlarla başa çıkmak oldukça kolaydır. $ _POST boşsa, en azından sorunun nerede olduğunu biliyorsunuzdur. – Sylverdrag

+0

Benim için çalışıyor! – jruzafa

cevap

112

Sen boş $_POST var. Eğer web sunucunuz json formatında veri görmek istiyorsa, ham girdiyi okumanız ve ardından JSON kod çözücüsü ile ayrıştırmanız gerekir.

CURLOPT_POSTFIELDS

application/x-www-form-urlencoded olarak parametrelerini kodlamak için curl söyler ...
$json = file_get_contents('php://input'); 
$obj = json_decode($json); 

Ayrıca test JSON-iletişim için yanlış kod var:

Böyle bir şey gerekiyor. Burada JSON-string'e ihtiyacınız var.

GÜNCELLEME test sayfasında

Kişisel php kod böyle olmalıdır:

$data_string = json_encode($data); 

$ch = curl_init('http://webservice.local/'); 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
     'Content-Type: application/json', 
     'Content-Length: ' . strlen($data_string)) 
); 

$result = curl_exec($ch); 
$result = json_decode($result); 
var_dump($result); 

Ayrıca web hizmeti sayfasında çizgiler header('Content-type: application/json'); birini kaldırmak gerekir. Sadece bir kez çağrılmalıdır.

başlıkta koymak sadece json yerine bir parametre içinde json koyup gönderebilirsiniz
+0

Teşekkürler Michael, bu büyük bir yardımcı oldu, düzenlememe bir göz atabilir ve sorunuma neden olan başka bir şey görüp göremeyeceğinizi görebilir misiniz? –

+1

Genel hatalarınızı göstermek için cevabımı güncelledim. –

+0

İnsan, bu çok yardımcı oldu! $ json = file_get_contents ('php: // input') kodu; $ obj = json_decode ($ json); Mükemmel bir şekilde çalışıyor – Cleversou

1

Merhaba Bu, bazı ücretsiz ip veri tabanları hizmetlerinden ip bilgi almak için curl kullanan eski bir projeden bir pasaj olduğunu json formatı. Sanırım size yardımcı olabilir.

$ip_srv = array("http://freegeoip.net/json/$this->ip","http://smart-ip.net/geoip-json/$this->ip"); 

getUserLocation($ip_srv); 

Fonksiyon:

function getUserLocation($services) { 

     $ctx = stream_context_create(array('http' => array('timeout' => 15))); // 15 seconds timeout 

     for ($i = 0; $i < count($services); $i++) { 

      // Configuring curl options 
      $options = array (
       CURLOPT_RETURNTRANSFER => true, // return web page 
       //CURLOPT_HEADER => false, // don't return headers 
       CURLOPT_HTTPHEADER => array('Content-type: application/json'), 
       CURLOPT_FOLLOWLOCATION => true, // follow redirects 
       CURLOPT_ENCODING => "", // handle compressed 
       CURLOPT_USERAGENT => "test", // who am i 
       CURLOPT_AUTOREFERER => true, // set referer on redirect 
       CURLOPT_CONNECTTIMEOUT => 5, // timeout on connect 
       CURLOPT_TIMEOUT => 5, // timeout on response 
       CURLOPT_MAXREDIRS => 10 // stop after 10 redirects 
      ); 

      // Initializing curl 
      $ch = curl_init($services[$i]); 
      curl_setopt_array ($ch, $options); 

      $content = curl_exec ($ch); 
      $err = curl_errno ($ch); 
      $errmsg = curl_error ($ch); 
      $header = curl_getinfo ($ch); 
      $httpCode = curl_getinfo ($ch, CURLINFO_HTTP_CODE); 

      curl_close ($ch); 

      //echo 'service: ' . $services[$i] . '</br>'; 
      //echo 'err: '.$err.'</br>'; 
      //echo 'errmsg: '.$errmsg.'</br>'; 
      //echo 'httpCode: '.$httpCode.'</br>'; 
      //print_r($header); 
      //print_r(json_decode($content, true)); 

      if ($err == 0 && $httpCode == 200 && $header['download_content_length'] > 0) { 

       return json_decode($content, true); 

      } 

     } 
    } 
+0

Kod parçacığı için teşekkürler, ancak sorunumun CURL kodundan ziyade webservice/PHP tarafında olduğunu düşünüyorum (her ne kadar bana% 100 olmadığımı söylemeye çekinmeyin). Benim PHP $ _POST değerlerim ve json_encoded veya başka bir şey olması gerekip gerekmediğini düşünüyorum. –

+0

hmm kıvrılma curl_setopt ($ curl, CURLOPT_UPLOAD, 1); – Syd

0

:

$json_string = $_POST['json_param']; 
$obj = json_decode($json_string); 
: Bir parametre olarak json dize alabilirsiniz hizmet tarafında

$post_string= 'json_param=' . json_encode($data); 

//open connection 
$ch = curl_init(); 

//set the url, number of POST vars, POST data 
curl_setopt($ch,CURLOPT_POST, 1); 
curl_setopt($ch,CURLOPT_POSTFIELDS, $post_string); 
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/'); // Set the url path we want to call 

//execute post 
$result = curl_exec($curl); 

//see the results 
$json=json_decode($result,true); 
curl_close($curl); 
print_r($json); 

daha sonra dönüştürülmüş verilerinizi nesne olarak kullanabilirsiniz.