PHP function to call JSON files - php

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
};

Related

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

How to read JSON file inside CodeIgniter Controller

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);

Loading a Search and Retrieve via URL (SRU) in php with simplexml_load_string returns an empty object

Im trying to load search result from an library api using Search and Retrieve via URL (SRU) at : https://data.norge.no/data/bibsys/bibsys-bibliotekbase-bibliografiske-data-sru
If you see the search result links there, its looks pretty much like XML but when i try like i have before with xml using the code below, it just returns a empty object,
SimpleXMLElement {#546}
whats going on here?
My php function in my laravel project:
public function bokId($bokid) {
$apiUrl = "http://sru.bibsys.no/search/biblio?version=1.2&operation=searchRetrieve&startRecord=1&maximumRecords=10&query=ibsen&recordSchema=marcxchange";
$filename = "bok.xml";
$xmlfile = file_get_contents($apiUrl);
file_put_contents($filename, $xmlfile); // xml file is saved.
$fileXml = simplexml_load_string($xmlfile);
dd($fileXml);
}
If i do:
dd($xmlfile);
instead, it echoes out like this:
Making me very confused that i cannot get an object to work with. Code i present have worked fine before.
It may be that the data your being provided ha changed format, but the data is still there and you can still use it. The main problem with using something like dd() is that it doesn't work well with SimpleXMLElements, it tends to have it's own idea of what you want to see of what data there is.
In this case the namespaces are the usual problem. But if you look at the following code you can see a quick way of getting the data from a specific namespace, which you can then easily access as normal. In this code I use ->children("srw", true) to say fetch all child elements that are in the namespace srw (the second argument indicates that this is the prefix and not the URL)...
$apiUrl = "http://sru.bibsys.no/search/biblio?version=1.2&operation=searchRetrieve&startRecord=1&maximumRecords=10&query=ibsen&recordSchema=marcxchange";
$filename = "bok.xml";
$xmlfile = file_get_contents($apiUrl);
file_put_contents($filename, $xmlfile); // xml file is saved.
$fileXml = simplexml_load_string($xmlfile);
foreach ( $fileXml->children("srw", true)->records->record as $record) {
echo "recordIdentifier=".$record->recordIdentifier.PHP_EOL;
}
This outputs...
recordIdentifier=792012771
recordIdentifier=941956423
recordIdentifier=941956466
recordIdentifier=950546232
recordIdentifier=802109055
recordIdentifier=910941041
recordIdentifier=940589451
recordIdentifier=951721941
recordIdentifier=080703852
recordIdentifier=011800283
As I'm not sure which data you want to retrieve as the title, I just wanted to show the idea of how to fetch data when you have a list of possibilities. In this example I'm using XPath to look in each <srw:record> element and find the <marc:datafield tag="100"...> element and in that the <marc:subfield code="a"> element. This is done using //marc:datafield[#tag='100']/marc:subfield[#code='a']. You may need to adjust the #tag= bit to the datafield your after and the #code= to point to the subfield your after.
$fileXml = simplexml_load_string($xmlfile);
$fileXml->registerXPathNamespace("marc","info:lc/xmlns/marcxchange-v1");
foreach ( $fileXml->children("srw", true)->records->record as $record) {
echo "recordIdentifier=".$record->recordIdentifier.PHP_EOL;
$data = $record->xpath("//marc:datafield[#tag='100']/marc:subfield[#code='a']");
$subData=$data[0]->children("marc", true);
echo "Data=".(string)$data[0].PHP_EOL;
}

Httpful JSON inside an array

I've been trying for 3 days to get PHP to show the ID from this test JSON using PHP and httpful.
Anyone have any ideas as i've tried loads of different combinations and even tried created a handler to decode as an array... I just suck at PHP ?
// Make a request to the GitHub API with a custom
// header of "X-Trvial-Header: Just as a demo".
<?php
include('\httpful.phar');
$url = "https://jsonplaceholder.typicode.com/posts";
$response = Httpful\Request::get($url)
->expectsJson()
->send();
echo "{$response[0]['id']}";
?>
My output... still nothing
You are not properly indexing the return value.
The response is a mixed value. So you should do something like below to get what you are looking for.
<?php
include('\httpful.phar');
$url = "https://jsonplaceholder.typicode.com/posts";
$response = Httpful\Request::get($url)
->expectsJson()
->send();
echo $response->body[0]->id;
?>

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.

Categories