将json数据从输入保存到数据库中

时间:2017-10-10 11:27:51

标签: php json laravel curl

我使用cURL作为输入获取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 个答案:

答案 0 :(得分: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);
    }