保存JSON数据到数据库

问题描述:

我得到使用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

不需要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正确答案再次检查 –