【问题标题】:Parse JSON data from file upload从文件上传解析 JSON 数据
【发布时间】:2018-10-11 20:29:45
【问题描述】:

我有一个选择 json 文件的输入

在我的控制器中,我做到了

dd(Input::all());

我明白了

我的目标是解析我得到的 JSON 文件并循环遍历它们。

我试过了

$string = file_get_contents(Input::get('fileinput'));
$json = json_decode($string, true);

我该如何继续?

【问题讨论】:

  • Input::get('fileinput') 返回什么?
  • 我不知道为什么它返回null
  • 我已经更新了我的答案,现在应该可以使用了!

标签: php json laravel laravel-5


【解决方案1】:

Input::get 用于从请求 ( $_REQUEST ) 中检索输入项, 您应该改用Input::file,它用于从请求中检索文件,并返回一个Illuminate\Http\UploadedFile 实例。

例子:

<?php
$file = Input::file('fileinput');
if($file === null) {
    throw new Exception('File was not sent !');
}
if($file->isReadable()) {
    $file->open('r');
    $contents = $file->fread($file->getSize());
    $json = json_decode($contents, true);
} else {
    throw new Exception('File is not readable');
}

Illuminate\Http\UploadedFile 扩展Symfony\Component\HttpFoundation\File\UploadedFile 扩展Symfony\Component\HttpFoundation\File\File 扩展SplFileInfo

【讨论】:

  • 我现在正在尝试。
  • 我做到了,我不断收到null
  • 什么返回 null ?
【解决方案2】:

我使用的是 Laravel 版本 6,其他解决方案不起作用。以下对我有用:

$file = request()->fileinput;      // <input type="file" name="fileinput" />
$content = file_get_contents($file);
$json = json_decode($content, true);

【讨论】:

    【解决方案3】:

    我这样做了,它对我有用

    Input::file('fileinput')->move(public_path(), 'fortinet_logs.json');
    $string = file_get_contents(public_path().'/fortinet_logs.json');
    $json = json_decode($string, true);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多