2017-10-10 5 views
0

に私は、入力としてのcURLを使用してJSONデータを取得:保存JSONデータデータベース

curl -H "Content-Type: application/json" -X GET http://localhost:8000/jsontest --data-binary @test.json 

それはフィールドのカップルと、単純なJSONです:

{ 
    "id": "12345", 
    "blockId": "9000", 
    "spot": { 
    "id": "7890", 
    "length": 23, 
    "name": "test", 
    "country": "de" 
    }, 
    "channel": "tv:rtl.de", 
    "startTimestamp": "1323872435345", 
    "endTimestamp": "13243498394384329" 
} 

そして、これがために私のコードですデータを取得してデータベースに保存する:

public function test() 
    { 
     $string = file_get_contents('php://input'); 

     $json_a = json_decode($string, true); 

     foreach ($json_a as $json => $test) { 
      $tvib   = new TVIB; 
      $tvib->spotid = $test["spot"]["id"]; 
      $tvib->name = $test["spot"]["name"]; 
      $tvib->channel = $test["channel"]; 
      $tvib->start = $test["startTimestamp"]; 
      $tvib->end  = $test["endTimestamp"]; 
      $tvib->save(); 
     } 

     var_dump($json_a); 
    } 

私はcURLリクエストを実行すると、このエラーとたくさんのhtmlとjsコードが得られます。

ErrorException: Illegal string offset 'spot' in file TestController.php on line 18 ($tvib->spotid = $test["spot"]["id"];) 

私はこのようなローカルでこれを実行する場合:

$string = file_get_contents('test.json'); 

すべてが正常に動作します。しかし、明らかにPHPの入力に問題があります。

提案がありますか?

PS私はLaravel 5.5を使用しています。

+1

json_doceode後$ json_a変数を印刷して、私にそれが入力からJSONを返して、出力 – javidrathod

+0

をお願いします。だから、私はそれが大丈夫だと思う。 – harunB10

+0

あなたのデータにエラーがあるので、出力してください。 – javidrathod

答えて

2

foreachは必要ありません。これにコードを変更します。

public function test() 
    { 
     $string = file_get_contents('php://input'); 

     $json_a = json_decode($string, true); 

     //foreach ($json_a as $json => $test) { 
      $tvib   = new TVIB; 
      $tvib->spotid = $json_a["spot"]["id"]; 
      $tvib->name = $json_a["spot"]["name"]; 
      $tvib->channel = $json_a["channel"]; 
      $tvib->start = $json_a["startTimestamp"]; 
      $tvib->end  = $json_a["endTimestamp"]; 
      $tvib->save(); 
     //} 

     var_dump($json_a); 
    } 
+0

複数のキーでJSONを取得した場合にforeachが必要です。私は未知のエラーが発生するため、この解決策は動作しません - $ testが見つかりません – harunB10

+0

@ harunB10変更コードと信頼されています。今編集しました –

+0

@ harunB10正解 –