How to read JSON file inside CodeIgniter Controller - php

I can't read my json file inside codeigniter controller, it returns an error.
My code:
$curYear = date("Y");
$string = file_get_contents(base_url("assets/data/".$curYear."_cal.json"));
Error Message return by my controller trying to read json file using:
file_get_contents(//localhost/EBR_Labeling/assets/data/2018_cal.json): failed to open stream: No such file or directory
Solved
Using this syntax:
file_get_contents("./assets/data/".$curYear."_cal.json")

Please use this code --
<?php
$json = file_get_contents(FILE_PATH);
$obj = json_decode($json);
echo '<pre>' . print_r($obj) . '</pre>';
?>
And let me know If you need any other help.
Thanks

We can simply store all json in views folder and can access it directly as follow:-
<?php
$countries = $this->load->view('countries.json', '', true) //this will load countries.json
$countries = json_decode($countries);
?>
Points to be noted : -
$this->load->view('countries') is same as writing $this->load->view('countries.php')
And this loads the view in browser and doesn't store it in variable. When we want some another type of file to be loaded, then we can simply change the extension.
$this->load->view('countries', $data, true);
Passing third parameter as true allows us to store the view in variable. If we don't want to pass second parameter then we can pass empty string as $this->load->view('countries', '', true);

Related

PHP function to call JSON files

I am trying to make a basic PHP function in order to call json files repeatedly throughout the app. Every time I want to call a json file I use:
<? $site = json_decode(file_get_contents('views/partials/site.json')); ?>
Then I use echo to use data from json file like this:
<? echo $site[0]->title; ?>
But instead of repeating part one I want to write a function in the header and call it where I want to call a json file. After that i was planning to use the function like this:
$site = jsonCall('site');
by using the function below;
function jsonCall($jsonurl){
// this is one line code. no difference from 3 lines below-> $jsonCalled = json_decode(file_get_contents($homepage . 'views/partials/' . $jsonurl . '.json'));
$url = $homepage . 'views/partials/' . $jsonurl . '.json';
$data = file_get_contents($url); // put the contents of the file into a variable
$jsonCalled = json_decode($data); // decode the JSON feed
echo $jsonCalled;
};
but instead of what i want i got an array as a response from server. i think my function turns json file to an array and that way i can't call it properly.
anyone knows how to solve this simple issue? show me proper way to write this function so my code might look a bit easier to read. Thank you.
by changing echo in function with return and using jsonCall('site')[0]->title; everything worked fine.
Of course you are getting an array. Otherwise $site[0] (which is an array access at key zero) would not have worked.
From the PHP docs (http://php.net/manual/en/function.json-decode.php):
Returns the value encoded in json in appropriate PHP type. Values
true, false and null are returned as TRUE, FALSE and NULL
respectively. NULL is returned if the json cannot be decoded or if the
encoded data is deeper than the recursion limit.
Your appropriate PHP type is array.
The following should work:
jsonCall('site')[0]->title;
Therefore I can not see a problem with your code?
The server is responding with Array because that is how PHP represents an array when you are echo'ing it. Your function should be returning the result.
Try:
function jsonCall($jsonurl){
// this is one line code. no difference from 3 lines below-> $jsonCalled = json_decode(file_get_contents($homepage . 'views/partials/' . $jsonurl . '.json'));
$url = $homepage . 'views/partials/' . $jsonurl . '.json';
$data = file_get_contents($url); // put the contents of the file into a variable
$jsonCalled = json_decode($data); // decode the JSON feed
// echo $jsonCalled;
return $jsonCalled; // <- this should work
};

How to extract an object within a JSON object in PHP and assign it the right index

I have the following PHP code (I'll post the important part of it):
// objID
$objects->objID = generateRandomID();
$objects->pointer = array('type'=>'__pointer','objID'=>'dgFg45dG','className'=>'Users');
$jsonStr = file_get_contents($className.'.json'); // This calls a Users.json file stored in my server
$jsonObjs = json_decode($jsonStr, true);
...
$jsonStr = file_get_contents($className.'.json'); // This calls a Users.json file stored in my server
$jsonObjs = json_decode($jsonStr, true);
array_push($jsonObjs, $objects);
// Encode the array back into a JSON string and save it.
$jsonData = json_encode($jsonObjs);
file_put_contents($className.'.json', $jsonData);
// echo JSON data
echo $jsonData;
// ISSUE HERE :(
$jsonStr = file_get_contents($className.'.json');
// Decode the JSON string into a PHP array.
$jsonObjs = json_decode($jsonStr, true);
foreach($jsonObjs as $i=>$obj) {
print_r('<br><br>'.$i.'-- ');
echo
$obj['objID'].', <br>'
.$obj['pointer']["$i"]['objID']. ', '
.$obj['pointer']["$i"]['type']. ', '
.$obj['pointer']["$i"]['className']. '<br><br>'
;
}
// ./ ISSUE
The code above creates a new JSON object into my own Users.json file.
So, when I call this PHP file with a URL string in my browser, just as a test, and I refresh the page a few times, I get the following echo:
0-- VUDjCZX8QX, , ,
1-- 1uWH17OoJP, , ,
[{"objID":"VUDjCZX8QX","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"mark","createdOn":"2018-09-17 05:36:49","updatedOn":"2018-09-17 05:36:49","number":111,"boolean":true,"array":["john","sarah"]},{"objID":"1uWH17OoJP","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"mark","createdOn":"2018-09-17 05:36:51","updatedOn":"2018-09-17 05:36:51","number":111,"boolean":true,"array":["john","sarah"]},{"objID":"RkubyQPvqR","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"mark","createdOn":"2018-09-17 05:36:54","updatedOn":"2018-09-17 05:36:54","number":111,"boolean":true,"array":["john","sarah"]}]
So, what I need to fix is basically the following:
What's the right code to properly get the list of items of the
"pointer" object that's inside each object of my Users.json file?
I try to track the index of my foreach loop, but it doesn't work properly as you can see by the echo posted above when I first execute my PHP code, I get the JSON string of my 1st object, I don't get any print_r(). Then, when I refresh the page a 2nd time, I get the print of the objID string of my 1st object, and again, if I refresh the page a 3rd time, I get the objID of my 2nd object, while there are 3 objects stored in my json file. And so on, in other words, I never get the first object's print info.
What am I doing wrong?
You are passing $i as a string, not as a variable. Use double quotes (") or remove single quotes (') to pass as a variable. This will solve your issue, pointer objects not printing properly.
$obj['pointer'][$i]['objID']
Update
[{"objID":"VUDjCZX8QX","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"mark","createdOn":"2018-09-17 05:36:49","updatedOn":"2018-09-17 05:36:49","number":111,"boolean":true,"array":["john","sarah"]},{"objID":"1uWH17OoJP","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"mark","createdOn":"2018-09-17 05:36:51","updatedOn":"2018-09-17 05:36:51","number":111,"boolean":true,"array":["john","sarah"]},{"objID":"RkubyQPvqR","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"mark","createdOn":"2018-09-17 05:36:54","updatedOn":"2018-09-17 05:36:54","number":111,"boolean":true,"array":["john","sarah"]}]
According to above JSON string, you don't need specify $i.
$obj['pointer']['objID'] should work, since it is associate array.
Thanks to #saumini-navaratnam, I have to use the following foreach:
foreach($jsonObjs as $i=>$obj) {
print_r('<br><br>'.$i.'-- ');
echo
$obj['objID'].', '
.$obj['pointer']['objID']. ', '
.$obj['pointer']['type']. ', '
.$obj['pointer']['className']. '<br><br>'
;
}
In this way, I can properly get the objects of this object:
{"pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"}
In fact, here's the echo I get:
[
{"objID":"pkO8NesS5S","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"bobby","createdOn":"2018-09-17 07:03:27","updatedOn":"2018-09-17 07:03:27","number":111,"boolean":true,"array":["john","sarah"]},
{"objID":"rdwJl20krC","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"bobby","createdOn":"2018-09-17 07:03:31","updatedOn":"2018-09-17 07:03:31","number":111,"boolean":true,"array":["john","sarah"]},
{"objID":"3WspzmuwMK","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"bobby","createdOn":"2018-09-17 07:07:39","updatedOn":"2018-09-17 07:07:39","number":111,"boolean":true,"array":["john","sarah"]}
]
0-- pkO8NesS5S, dgFg45dG, __pointer, Users
1-- rdwJl20krC, dgFg45dG, __pointer, Users
2-- 3WspzmuwMK, dgFg45dG, __pointer, Users

Use PHP to parse INI file and run JSON_DECODE

I'm looking to get some input on how to make modular code that performs a PHP parse_ini_file and then uses the returned values to run JSON decodes.
I have a BACnet API that returns a JSON structure for BACnet points in an automation system. I wrote the following code to decode the JSON data to return just the "present-value" field and then I display the value on a webpage.
<?php
$url = "http://hostname.lcl:47800/api/v1/bacnet/devices/10100/objects/0.0";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "<b>Room temperature</b>: ". $json_data["present-value"]. " DEG F";
;?>
This works well but I want to make this code modular so it can be used for many other points.
I created an INI file with a list of other points and the URL that contains the JSON data from the API.
## BACnet Configuration File
# BACnet Object URLs from WACNET Browser API
[bacnet]
SEA_RMT = http://hostname.lcl:47800/api/v1/bacnet/devices/10100/objects/0.0
SEA_SRV_SEA_SV1_01_EXHT = http://hostname.lcl:47800/api/v1/bacnet/devices/10100/objects/0.3
SEA_SRV_SEA_SV1_02_EXHT = http://hostname.lcl:47800/api/v1/bacnet/devices/10100/objects/0.4
SEA_SRV_SEA_SV1_03_EXHT = http://hostname.lcl:47800/api/v1/bacnet/devices/10100/objects/0.5
What I'd like to do is use the INI file to get the present value of each point in the list and then create a variable that is the name of the point and set it equal to the "present-value" field. Then I can reference the point using the PHP variable on the HTML page like this:
<?php echo "$SEA_SRV_SEA_SV1_01_EXHT";?>
I started with the code below but it doesn't work.
<?php
// Parse the settings file
$bacnetini = parse_ini_file('/var/www/config/bacnet.ini');
// Parse the keys to variables and add data
foreach ($bacnetini as $key => $value) {
$url = $value;
$json = file_get_contents($url);
$json_data = json_decode($json, true);
$$key = $json_data;
}
?>
I'd love to get some other opinions on the best way to accomplish this since I don't really know where to go from here.
I've looked through these other Stack Overflow questions but I don't know how to get the pieces to all fit together.
Parsing a config file in php to variables
Get JSON object from URL
Why not try something like this instead? This will allow you to create other sections in your INI file that won't affect your script.
<?php
$bacnetini = parse_ini_file('/var/www/config/bacnet.ini', true);
$data = array();
foreach ($bacnetini['bacnet'] as $key => $url) {
$data[$key] = json_decode(file_get_contents($url), true);
}
var_dump($data['SEA_SRV_SEA_SV1_01_EXHT']);
?>

Get a JSON from url with PHP

Im new to php and tried to get a json object from the twitch API to retrieve one of its values and output it. i.e
i need to get the information from this link: https://api.twitch.tv/kraken/users/USERNAME/follows/channels/CHANNELSNAME
plus i need to to something so i can modify the urls USERNAME and CHANNELSUSERNAME. I want it to be a api to call for howlong user XY is following channelXY and this will be called using nightbots $customapi function.
the date i need from the json is "created_at"
Since we were able to clear out the errorsheres the final PHP file that works if anyone encounters similiar errors:
<?php
$url = "https://api.twitch.tv/kraken/users/" . $_GET['username'] . "/follows/channels/" . $_GET['channel'];
$result = file_get_contents($url);
$result = json_decode($result, true);
echo $result["created_at"];
?>
You have a typo in your code on the first line and you're not storing the result of your json_decode anywhere.
<?php
$url = "https://api.twitch.tv/kraken/users/" . $_GET['username'] . "/follows/channels/" . $_GET['channel'];
$result = file_get_contents($url);
$result = json_decode($result, true);
echo $result["created_at"];
You have to call the page this way page.php?username=yeroise&channel=ceratia in order to output the created_at value for this user and this channel.
In your code you're using 2 different ways to get the content of the page and you only need one (either file_get_contents or using CURL), I chose file_get_contents here as the other method adds complexity for no reason in this case.

json_decode to an array?

foreach ($likes as $like) {
// Extract the pieces of info we need from the requests above
$id = idx($like, 'id');
$item = idx($like, 'name');
fwrite($fileout,json_encode($like));
fwrite($fileout,PHP_EOL );
}
$json_string = file_get_contents('testson.json');
$get_json_values=json_decode($json_string,true);
foreach ($get_json_values as $getlikes) { ?>
<li>
<a href="https://www.facebook.com/<?php echo $getlikes['id']; ?>" target="_top">
</li>
<?php
}
When opening the browser, there is a Warning: Invalid argument supplied for foreach(). I don't understand why would my arguments be invalid.
If I add the if, nothing happens, which shows what the actual problem is. But the question is WHAT IS THE PROPER WAY TO DO THIS? I'm pretty sure it's very simple, but i've been struggling with this for more than an hour. My json files has fields like this, so I don't think there would be the problem:
{"category":"Musician\/band","name":"Yann Tiersen (official)","id":"18359161762"}
Please help me, I really got tired with it, and I don't know what to do. So... how can I decode the file into an array?
You need the contents of the testson.json file not just the name!
Receive the contents via PHP:
$json_string = file_get_contents('testson.json');
Make sure there are valid JSON contents in the file by testing it via
var_dump(json_decode($json_string));
And then call
foreach (json_decode($json_string) as $getlikes) { ?>
Update:
When you save the file and access it miliseconds later it might be that the filesystem is too slow and not showing you the correct content.
Add
fclose($fileout);
clearstatcache();
before the file_get_contents(); call!
I recommend to use file_put_contents() and file_read_contents() to get
rid of such problems!
json_decode is expecting a string as it's first parameter. You are passing what I'm guessing is a filename. You should load the file first like so...
$json = file_get_contents('testson.json');
$data = json_decode($json);

Categories