2017-10-10 196 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變量,並給我輸出 – javidrathod

+0

它返回從輸入JSON。所以,我認爲這很好。 – harunB10

+0

PLease打印並給我那個輸出,因爲它會給出錯誤,因爲你的數據有錯誤。 – 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

我需要foreach才能使用多個鍵獲取JSON。順便說一句,這種解決方案不起作用,因爲我得到一個未知的錯誤 - $未找到測試 – harunB10

+0

@ harunB10更改代碼和trusted.i'm現在編輯 –

+0

@ harunB10正確答案再次檢查 –