code-8
code-8

Reputation: 58810

Parse JSON data from file upload

I have an input that select json file

In my controller, I did

dd(Input::all());

I got

enter image description here

My goal is to parse the JSON file that I got and loop through them.

I've tried

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

How can I proceed?

Upvotes: 0

Views: 2180

Answers (3)

Muhammad Inaam Munir
Muhammad Inaam Munir

Reputation: 1260

I am using Laravel version 6 and the other solutions did not work. Following worked for me:

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

Upvotes: 0

azjezz
azjezz

Reputation: 3987

Input::get is used to retrieve an input item from the request ( $_REQUEST ), you should use Input::file instead, which is used to retrieve a file from the request, and returns a Illuminate\Http\UploadedFile instance.

example :

<?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 extends Symfony\Component\HttpFoundation\File\UploadedFile extends Symfony\Component\HttpFoundation\File\File extends SplFileInfo

Upvotes: 2

code-8
code-8

Reputation: 58810

I did this and it works for me

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

Upvotes: -1

Related Questions