I have an input that select json file
In my controller, I did
dd(Input::all());
I got
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?
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
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);
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);
Related
I send the following data to my php file via ajax:
JSON.stringify({test1: '1', test2: '2'})
I would like to write this data to my JSON FILE content.json containing an empty array
[]
I only want to add the content though if it is not there, yet. This is my PHP code:
$jsonStringObject = file_get_contents("php://input");
$phpObject = json_decode($jsonStringObject);
$newJsonStringObject = json_encode($phpObject);
header('Content-Type: application/json');
$jsonString = file_get_contents('content.json');
$data = (array) json_decode($jsonString, true);
if (in_array($phpObject, $data) === false){
$data[] = $phpObject;
}
$newJsonString = json_encode($data);
file_put_contents('content.json', $newJsonString);
It almost works. Something is wrong with the way the data is added to the array because when I call the function for the first time, it updates content.json to
[null,{"test1":"1","test2":"2"}]
On calling the function again, it adds the object again despite the if-statement:
[null,{"test1":"1","test2":"2"},{"test1":"1","test2":"2"},{"test1":"1","test2":"2"}]
Can anyone help me to spot the mistake?
You're comparing apples and oranges (or rather objects to arrays).
Make sure you decode all json as arrays:
$jsonStringObject = file_get_contents("php://input");
// Added true as second argument to get it bas as an array
$phpObject = json_decode($jsonStringObject, true);
$jsonString = file_get_contents('content.json');
// Removed the (array) since the second argument literally means "return as array"
$data = json_decode($jsonString, true);
if (in_array($phpObject, $data) === false){
$data[] = $phpObject;
}
$newJsonString = json_encode($data);
file_put_contents('content.json', $newJsonString);
Demo: https://3v4l.org/rnCn5
So I decided to make my own helper in Codeigniter to get JSON files and save PokeAPI calls as JSON.
The save JSON method I created works fine:
if ( ! function_exists('saveJson')) {
function saveJson($file, $data) {
$fp = fopen($file, 'w');
fwrite($fp, json_encode($data));
fclose($fp);
}
}
However the getJSON function works very randomly. It works for fetching certain files but others it throws this error: Message: json_decode() expects parameter 1 to be string, array given. (all json files are the same format)
getJSON function:
if ( ! function_exists('getJson')) {
function getJson($file) {
$json = file_get_contents($file);
$data = json_decode($json, true);
$pkm = json_decode($data, true);
return $pkm;
}
}
Its odd, I have to decode the JSON twice or can I cannot access the array in my views.
My model and controller for further depth on the issue:
Model function example:
function getPokemonById($id) {
$filepath = './assets/jsonsaves/pokemoncalls/'. $id. '.json';
if(file_exists($filepath)) {
$pokemonByIdData = getJson($filepath);
} else {
$url = $this->pokemonApiAddress.$id.'/';
$response = Requests::get($url);
saveJson($filepath, $response);
$pokemonByIdData = json_decode($response->body, true);
}
return $pokemonByIdData;
}
Controller function example:
public function viewPokemon($id) {
$singlePokemon['pokemon'] = $this->pokemon_model->getPokemonById($id);
$singlePokemon['species'] = $this->pokemon_model->getPokemonSpecies($id);
$data['thepokemon'] = $this->pokemon_model->getAllPokemon();
$this->load->view('template/header', $data);
$this->load->view('pokemonpage', $singlePokemon);
$this->load->view('template/footer');
}
So there is some variation in my JSON file. In one JSON file that does not work it has, at the beginning:
{"body":"{\"forms\":[{\"url\":\"https:\\\/\\\/pokeapi.co\\\/api\\\/v2\\\/pokemon-form\\\/142\\\/\",\"name\":\"aerodactyl\"}],...
However this one works:
"{\"forms\":[{\"url\":\"https:\\\/\\\/pokeapi.co\\\/api\\\/v2\\\/pokemon-form\\\/6\\\/\",\"name\":\"charizard\"}],...
I fixed the issue thanks to #ccKep.
I removed the JSON encode from my saveJSON function like so:
if ( ! function_exists('saveJson')) {
function saveJson($file, $data) {
$fp = fopen($file, 'w');
fwrite($fp, $data);
fclose($fp);
}
}
And then removed the second json_decode from my getJSON function:
if ( ! function_exists('getJson')) {
function getJson($file) {
$json = file_get_contents($file);
$data = json_decode($json, true);
return $data;
}
}
This fixed the errors I was receiving.
I made simple text editor and now working on image upload and image manager. I have set up manager to read .json file with all images and it works ok. The problem is for php script to actually write newly added images to that json.
$file = "images.json";
$arr_data = array();
foreach(glob('/uploads/*') as $image) {
$arr_data = array(
'link' => $image,
'tag' => 'images',
);
}
$jsondata = file_get_contents($file);
$arr_data = json_decode($jsondata, true);
array_push($arr_data,$jsondata);
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents($file, $jsondata));
I am getting
Warning: array_push() expects parameter 1 to be array
even tho array data is provided. How to solve this?
If you are starting with an empty file i.e. images.json then the first time you run these 2 lines
$jsondata = file_get_contents($file);
$arr_data = json_decode($jsondata, true);
the second line will change $arr_data into a boolean probably. As json_decode() will fail to convert nothing into an array.
So add this to initialize the file for use
<?php
$file = "images.json";
file_put_contents($file, '[]'); // init the file
You are also reusing the $arr_data variable so amend this also and you are overwriting the new array as well
$file = "images.json";
file_put_contents($file, '[]'); // init the file
$arr_data = array();
foreach(glob('/uploads/*') as $image) {
// amended to not reuse $arr_data
// ameded to not overwrite the array as you build it
$new_arr[] = array( 'link' => $image, 'tag' => 'images');
}
$jsondata = file_get_contents($file);
$arr_data = json_decode($jsondata, true);
array_push($arr_data,$new_arr);
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents($file, $jsondata));
I have a json file which is read by php and i want to change one object of the json file using php now my code looks like this but it doesn't work so how should I do? (the obj_name in the son object should be modified to $name)
<?php
$json = $_POST['myobj'];
$data = json_decode($json,true);
$name = xxxxxxxxx;
$data['obj_name'] = "$name";
#json = json_encode($data);
$filename = xxxxxxxxxxxxx
$file = fopen($filename,'w+');
fwrite($file, $json);
fclose($file);
?>
The # is commenting out your code and it should be a $ to make it a variable.
So, change this:
#json = json_encode($data);
to this:
$json = json_encode($data);
I want to retrieve array value.
This is my array value:
overlay.txt:
{"title":"sss","description":"sss","code":"sss"}
{"title":"trtr","description":"trtr","code":"tyrytr"}
{"title":"ret54","description":"56tr","code":"ty76"}
{"title":"rgfdg","description":"dfgdfg","code":"dfgdfg"}
{"title":"asfafdsf","description":"sdfsdf","code":"sdfsdfsdf"}
This is my code: but this is not working.why?
How to retrieve value from overlay.txt file.
I did not get all title value.
I do not known how to get title value from overlay.txt
The $title is showing empty.
Where I want to change in my code to get $title value.
$info = array();
$folder_name = $this->input->post('folder_name');
$info['title'] = $this->input->post('title');
$info['description'] = $this->input->post('description');
$info['code'] = $this->input->post('code');
$json = json_encode($info);
$file = "./videos/overlay.txt";
$fd = fopen($file, "a"); // a for append, append text to file
fwrite($fd, $json);
fclose($fd);
$filecon = file_get_contents('./videos/overlay.txt', true);
$this->load->view('includes/overlays',$filecon);
//overlays page;
foreach($filecon as $files)
{
$title=$files['title'];
echo $title;
}
You're encoding your array to JSON, so at some point you need to decode it again into a PHP array. Since you actually have several JSON objects in the file, you need to decode each one individually. Assuming it's always one JSON object per line, this'll do:
$jsonObjects = file('overlay.txt', FILE_IGNORE_NEW_LINES);
foreach ($jsonObjects as $json) {
$array = json_decode($json, true);
echo $array['title'];
...
}
This will very quickly break if there are line breaks within the serialized JSON, e.g.:
{"title":"ret54","description":"foo
bar","code":"ty76"}
That way of storing the data is not very reliable.
make overlay.txt fully json format:
[
{"title":"sss","description":"sss","code":"sss"},
{"title":"trtr","description":"trtr","code":"tyrytr"},
...
]
and try this:
$raw = file_get_contents('./videos/overlay.txt', true);
$this->load->view('includes/overlays', array("filecon" => json_decode($raw)));
overlay page:
<?php
foreach($filecon as $files) {
echo $files['title'];
}
?>
If you want to use $filecon in view file,
set an array which has the key "filecon" in $this->load->view()'s second argument.
http://codeigniter.com/user_guide/general/views.html