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.
Related
I have this in my text tile
[{"id":20,"tokenType":"Keyfob","tokenValue":"9037119","isLost":false}][{"id":22,"tokenType":"Keyfob","tokenValue":"47690743","isLost":false}]
But i am trying to convert it to json object like this below:
$cache_file = $_SERVER['DOCUMENT_ROOT']."/site/users/sample-keys-test.txt";
$file = fopen($cache_file, "r");
$file_content = fread($file, filesize($cache_file));
$file_content = preg_replace("/\[(.*?)\]/", "$1,", $file_content);
$file_content = rtrim($file_content, ",");
$data = json_decode("{\"items\": [".$file_content."]}", true);
var_dump($data);
foreach($data["items"] as $json_object) {
// Do something with each JSON object
echo $json_object["id"]."<br>";
echo $json_object["tokenType"]."<br>";
echo $json_object["tokenValue"]."<br>";
echo $json_object["isLost"]."<br>";
}
fclose($file);
But in the line with var_dump i get null which means there is something wrong with converting it to json object.
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
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);
In magento as we use the rest url to access the data, as http://localhost/magento/api/rest/products it returns in xml format instead of that I need JSON.
I have tried below code, but no use
$this->getResponse()->setHeader('Content-type', 'application/json');
$this->getResponse()->setBody($jsonData);
in the folder \magento\app\code\core\Mage\Api\Controller\Action.php
vinox, you should override the default file Request.php. copy \app\code\core\Mage\Api2\Model\Request.php to your local directory and add the following code just before end of the getAcceptTypes() Method.
unset($orderedTypes);
$orderedTypes=Array("application/json" => 1);
in other way your getAcceptTypes() method should look like this.
public function getAcceptTypes(){
$qualityToTypes = array();
$orderedTypes = array();
foreach (preg_split('/,\s*/', $this->getHeader('Accept')) as $definition) {
$typeWithQ = explode(';', $definition);
$mimeType = trim(array_shift($typeWithQ));
// check MIME type validity
if (!preg_match('~^([0-9a-z*+\-]+)(?:/([0-9a-z*+\-\.]+))?$~i', $mimeType)) {
continue;
}
$quality = '1.0'; // default value for quality
if ($typeWithQ) {
$qAndValue = explode('=', $typeWithQ[0]);
if (2 == count($qAndValue)) {
$quality = $qAndValue[1];
}
}
$qualityToTypes[$quality][$mimeType] = true;
}
krsort($qualityToTypes);
foreach ($qualityToTypes as $typeList) {
$orderedTypes += $typeList;
}
unset($orderedTypes);
$orderedTypes=Array("application/json" => 1);
return array_keys($orderedTypes);
}
I guess your $jsonData is not actually JSON. Try using a json helper
$jsonData = Mage::helper('core')->jsonEncode($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