我得到使用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
請打印json_doceode後$ json_a變量,並給我輸出 – javidrathod
它返回從輸入JSON。所以,我認爲這很好。 – harunB10
PLease打印並給我那個輸出,因爲它會給出錯誤,因爲你的數據有錯誤。 – javidrathod