2013-09-25 7 views
51

私はこの質問を投稿する前に多くを見ていましたので、別の投稿にありましたら謝罪します。PHPを使用してJSON POSTを読む

ポスト値を取得してJSONエンコードされた配列を返す必要がある、私が作成した本当にシンプルなWebサービスがあります。それは、アプリケーション/ jsonのコンテンツタイプを持つフォームデータを投稿する必要があると言われるまで、すべてうまくいきました。それ以来、私はWebサービスからどのような値も返すことができません。それは間違いなく、投稿値をどのようにフィルタリングしているのかとは関係ありません。 (私は機能の一部を取り除かれている)私はこれを持っているWebサービスで

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

- -

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

?> 
を基本的に私の地元のセットアップで、私は以下のことを行い、テストページを作成している

基本的には、$ _POSTの値が設定されていないためですが、$ _POSTの代わりに配置する必要があるものは見つかりません。私は json_decode($ _ POST)、file_get_contents( "php:// input")など数多くの方法を試しましたが、暗闇の中で何度も撮影していました。

ご協力いただければ幸いです。私はポストをエコーする際の助けを

おかげで、スティーブ

おかげでマイケルは、それが前進明確なステップだった私は今、少なくともそれがnullの場合でも

が更新.... repsonseを持っています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)); 
データはに投稿されたページの

更新PHP -

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

print_r(json_encode($input)); 

少なくとも私は空白のページを返す前に応答を見るようになった。

+0

エラーが何であるかはわかりませんが、最初のステップでは、$ _POSTの内容をトレンチアウトして内容を確認します。データがあれば、それを処理するのはかなり簡単です。 $ _POSTが空の場合は、少なくとも問題がどこにあるかを知っています。 – Sylverdrag

+0

それは私のために働く! – jruzafa

答えて

112

あなたは$_POST空を持っています。 Webサーバーがjson形式のデータを表示したい場合は、生の入力を読み込んでJSONデコードで解析する必要があります。

あなたはそのような何かが必要です。

CURLOPT_POSTFIELDSapplication/x-www-form-urlencodedとして、あなたのパラメータをエンコードするcurlを伝えます...また、あなたがテストJSON-通信のために間違ったコードを持って

$json = file_get_contents('php://input'); 
$obj = json_decode($json); 

を。ここにJSON文字列が必要です。テストページ用

PHPコードは、そのようにする必要があり

UPDATE:

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

また、Webサービスのページでは、ラインheader('Content-type: application/json');の1を削除する必要があります。一度だけ呼び出さなければなりません。

あなたは、ヘッダーに置くだけで、あなたのJSONの代わりにパラメータであなたのJSONを入れて、それを送ることができます
+0

マイケルさん、大きな助けをしてくれてありがとうございました。私の編集を見て、自分の問題の原因となっていることが他に見えるかどうか確認できますか? –

+1

一般的な間違いを示すために私の答えが更新されました。 –

+0

男、これはとても役に立ちました!コード $ json = file_get_contents( 'php:// input'); $ obj = json_decode($ json); 完全に働いた – Cleversou

1

こんにちはこれはcurlを使っていくつかのフリーIPデータベースサービスからip情報を取得する古いプロジェクトのスニペットですjsonフォーマット。私はそれがあなたを助けるかもしれないと思う。

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

getUserLocation($ip_srv); 

機能:

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

コードスニペットありがとうございますが、私は自分の問題がCURLコードではなくwebservice/PHP側にあると思います(ただし、100%ではないので私に教えてください)。私はそれが私のPHP $ _POST値であり、json_encodedか何か他のものである必要があるかどうかと思います。 –

+0

hmmこれをカールに追加してみてください。curl_setopt($ curl、CURLOPT_UPLOAD、1); – Syd

0

$json_string = $_POST['json_param']; 
$obj = json_decode($json_string); 
:あなたは、パラメータとして、あなたのJSON文字列を取得することができ、サービス側に

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

変換したデータをオブジェクトとして使用することができます。

関連する問題