【发布时间】: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。所以,我认为没关系。
-
请打印并给我那个输出,因为它给出了错误,因为你的数据有错误。