【问题标题】:Save json data from input into database将输入的json数据保存到数据库中
【发布时间】:2018-03-21 19:03:08
【问题描述】:

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

【问题讨论】:

  • 请在 json_doceode 之后打印 $json_a 变量并给我那个输出
  • 它正在从输入中返回 json。所以,我认为没关系。
  • 请打印并给我那个输出,因为它给出了错误,因为你的数据有错误。

标签: php json laravel curl


【解决方案1】:

不需要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);
    }

【讨论】:

  • 我需要 foreach 以防我得到带有多个键的 JSON。顺便说一句,这个解决方案不起作用,因为我收到一个未知错误 - $test not found
猜你喜欢
  • 2013-04-06
  • 2012-04-05
  • 1970-01-01
  • 2016-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-14
  • 1970-01-01
相关资源
最近更新 更多