Output json to php (frontend) - php

Here is the output as its beeing displayed right now in my index file (on the wesbite)
So this is what i have right now
https://gyazo.com/e3b5efb2c0ac9c7225c5c322ae92b0e9
And i want to have that displayed more nicley ( perhaps in a table with header from and then text )
That is my problem, im usure of what i can google or search for. Get the data that is saved in my json file. And Display it nicley in my index.
Get some of the values from my .json file and display them in my index.
Here is my php code.
$outfile= 'result.json';
$url='https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=MYAPIKEY';
$json = file_get_contents($url);
if($json) {
if(file_put_contents($outfile, $json, FILE_APPEND)) {
echo "Saved JSON fetched from “{$url}” as “{$outfile}”.";
}
else {
echo "Unable to save JSON to “{$outfile}”.";
}
}
else {
echo "Unable to fetch JSON from “{$url}”.";
}
$option = $_GET['option'];
And here its how i's getting displayed in my .json file.
{"status":"ok","totalResults":20,"articles":[{"source":{"id":"cnn","name":"CNN"},"author":"Matt McFarland","title":"Has Elon Musk lost control of his hype machine?","description":"For years, the entrepreneur controlled public opinion of Tesla. That's changing.","url":"https://money.cnn.com/2018/07/26/technology/elon-musk-tesla/index.html",

You might have invalid json response. verify first whether do you have valid json. May be copy your response and check it in some validator website like www.jsonlnt.com
if json is fine then PHP function json_decode($you_json_string_php_variable); will work fine.

Related

PHP, split received POST data after few words or sentences

I am able to send JSONObject data from my application to server with PHP. I am also able to read the data. But now I want to send the data with a USER ID and type of data in the first two sentences. I am able to send this data from my application.
But I am not experienced with working on PHP and I dont know how to split this data after reading USER id and the type I have received and to store the rest of data separately ( and should be stored as json data with USER ID as filename).
Currently I am using the following to just save the
<?php
$content = file_get_contents('php://input');
$data = json_decode($content, true);
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($data));
fclose($fp);
if(!is_array($data)){
throw new Exception('Received content contained invalid JSON!');
}
echo "Data Received";
?>
This is the json data format,
[{ "increment_id": "1", "uuid": "43c87b6e-4fd5-4f1b-9bba-3e512eb4787a", "xValue": "39.0", "yValue": "72.0", "inputTime": "Thu Mar 08 15:38:58" }]
I also want to attach user id with it, which I am able to attach and send it to server, but I cannot use json decode now as the format changes to re encode if I give a userid with it in the first sentence . So after attaching userid and type the data looks like this
UserID Type [{ "increment_id": "1", "uuid": "43c87b6e-4fd5-4f1b-9bba-3e512eb4787a", "xValue": "39.0", "yValue": "72.0", "inputTime": "Thu Mar 08 15:38:58" }]
What sentences? Send it where? Its far from clear what you are asking.
I dont know how to split this data
We don't either. What do you mean by split? That implies there's going to more than one data item - where do you want to split it? What do you want to do with the 2 parts?
should be stored as json data with USER ID as filename
It is very unlikely that it should be stored where you are currently putting it - particularly when you are applying no validation to the data you saved.
Consider (and note the differences with your script):
<?php
define("DEST_DIR", "/not/in/your/document/root/");
$content = file_get_contents('php://input');
$data = json_decode($content, true);
if (isset($data['USER'])) {
$filename=basename($data['USER']);
$filename="data_" . array_shift(explode('.', $filename) . 'json';
file_put_contents(DEST_DIR . $filename);
print json_encode(array('result'=>'success'));
} else {
header("Bad Request", true, 400);
print json_encode(array('result'=>'bad input data');
}

Extracting a precise value from a Json array with PHP (like a MySQL db)

another (probably) easy question for you.
As I wrote many times, I'm not a programmer but thanks to you I was able to build an interesting site for my uses.
So again thx.
This is my new problem:
I have a site that recover json data from a file and store it locally once a day (this is the code - I post it so it can be useful to anyone):
// START
findList();
function findList() {
$serverName = strtolower($_POST["Server"]); // GET SERVER FROM FORM POST
$localCoutryList = ("json/$serverName/countries.json"); // LOCAL LOCATIONS OF FILE
$urlCountryList = strtolower("url.from.where.I.get.Json.file.$serverName/countries.json"); // ONLINE LOCATION OF FILE
if (file_exists($localCoutryList)) { // FILE EXIST
$fileLastMod = date("Y/m/d",filemtime($localCoutryList)); // IF FILE LAST MOD = FILE DATE TIME
$now = date('Y/m/d', time()); // NOW
if ($now != $fileLastMod) { // IF NOW != FILE LAST MOD (date)
createList($serverName,$localCoutryList,$urlCountryList); // GO AND CREATE FILE
} else { // IF NOW = FILE LAST MOD (date)
jsonList($serverName,$localCoutryList,$urlCountryList); // CALL JSON DATA FROM FILE
}} else { // FILE DOESN'T EXIST
createList($serverName,$localCoutryList,$urlCountryList); // CALL CREATE FILE
}};
function createList($serverName,$localCoutryList,$urlCountryList) {
file_put_contents($localCountryList, file_get_contents($urlCountryList)); // CREATE FILE
jsonList($serverName); // CALL JSON DATA FROM FILE
};
function jsonList($serverName,$localCoutryList,$urlCountryList) { // JSON DATA FROM FILE
$jsonLoopCountry = file_get_contents($localCoutryList); // GET CONTENT OF THE LOCAL FILE
$outLoopCountry = json_decode($jsonLoopCountry, true); // DECODE JSON FILE
$countryList = $outLoopCountry['country']; // ACCESS TO JSON OBJECT
foreach ($countryList as $dataCountry) { // FOR EACH "COUNTRY" IN JSON DECODED OBJECT
// SET VARS FOR ALL THE COUNTRIES
$iscountryID = ($dataCountry['id']); // TEST
$countryCurrency = ($dataCountry['curr']); // TEST
$countryName = ($dataCountry['name']);} // TEST
echo "<br>total country list: ".count($countryList); // THIS RETURN TOTAL ELEMENTS IN THE ARRAY
[...]
The kind of Json data I'm working with is structured as it follows:
{"country":[{"id":130,"curr":"AFN","name":"Afghanistan"},{"id":55,"curr":"ALL","name":"Albania"},{"id":64,"curr":"DZD","name":"Algeria"},{"id":65,"curr":"AOA","name":"Angola"},{"id":24,"curr":"ARS","name":"Argentina"}...
So I can say that
$outLoopCountry = json_decode($jsonLoopCountry, true); // DECODE JSON FILE
creates the JSON ARRAY right? (Because JSON array starts with {"something":[{"..."...)
if it was [{"a":"answer","b":"answer",...} ... it would have a been a JSON Object right?
So to access to the array I uses
$countryList = $outLoopCountry['country']; // ACCESS TO JSON OBJECT
right?
So I understood that arrays are a fast useful ways to store relational data and access to it right?
So the question is how to make a precise search inside the array, so to make it works like a Query MySQLi, like "SEARCH INSIDE ARRAY WHERE id == 7" and have as a result "== ITALY" (ex.).
The way exist for sure, but with whole exmples I found on the net, I was able to fix one to make it works.
Thx again.
Alberto

Unable to get stat gathering to work

Using PHP to gather stats from multiple files. Goal is to take the entire first row of data, which is the column name, then take the entire row of data from the row where the first column matches the name specified in the code. These two rows should then be linked to each other, so they can be displayed in a dynamic image.
However, to avoid excessive requests from the external data source, the data is only downloaded once a day by saving it into a json file. The previous day's data is also kept, to perform a difference calculation.
What I'm stuck on is...well, it's not working as intended. The dynamic image does not display and says it cannot be displayed because it contains errors, and the files aren't being created properly. Without any files existing, only the 'old' data file is being created, and the gathered data is saved there in a format that I didn't expect.
Here's the entire PHP code:
<?php
header("Content-Type:image/png");
$root=realpath($_SERVER['DOCUMENT_ROOT']);
function saveTeamData(){
$urls=array('http://www.dc-vault.com/stats/bio.txt','http://www.dc-vault.com/stats/math.txt','http://www.dc-vault.com/stats/misc.txt','http://www.dc-vault.com/stats/overall.txt','http://www.dc-vault.com/stats/phys.txt');
$fullJson=array();
function stats($url){
$json=array();
$team=array("teamName");
$file=fopen($url,'r');
$firstRow=fgetcsv($file,0,"\t");
while($data=fgetcsv($file,0,"\t")){
if(in_array($data[0],$team)){
foreach($firstRow as $indx=>$colName){
if((strpos($colName,'Position')!=0)||(strpos($colName,'Score')!=0)||(strpos($colName,'Team')!=0)){
if(strrpos($colName,'Position')!==false){
$colName=substr($colName,0,strpos($colName,' Position'));
$colName=$colName."Pos";
}else{
$colName=substr($colName,0,strpos($colName,' Score'));
$colName=$colName."Score";
}
$colName=str_replace(' ',',',$colName);
$teamData[$colName]=$data[$indx];
}
}
$json=$teamData;
}
}
fclose($file);
return $json;
}
foreach($urls as $item){
$fullJson=array_merge($fullJson,stats($item));
}
$final_json['teamName']=$fullJson;
$final_json['date']=date("Y-m-d G:i:s",strtotime("11:00"));
$final_json=json_encode($final_json);
file_put_contents("$root/scripts/vaultData.js",$final_json);
return $final_json;
}
if(!file_exists("$root/scripts/vaultData.js")){
$teamData=saveTeamData();
}else{
$teamData=json_decode(file_get_contents("$root/scripts/vaultData.js"));
}
$lastDate=$teamData->date;
$now=date("Y-m-d G:i:s");
$hours=(strtotime($now)-strtotime($lastDate))/3600;
if($hours>=24||!file_exists("$root/scripts/vaultDataOld.js")){
file_put_contents("$root/scripts/vaultDataOld.js",json_encode($teamData));
$teamData=saveTeamData();
}
$team=$teamData->{"teamName"};
$teamOld=json_decode(file_get_contents("$root/scripts/vaultDataOld.js"))->{"teamName"};
$template=imagecreatefrompng("$root/images/vaultInfo.png");
$black=imagecolorallocate($template,0,0,0);
$font='images/fonts/UbuntuMono-R.ttf';
$projects=array();
$subsections=array();
foreach($team as $key=>$val){
$projectName=preg_match("/^(.*)(?:Pos|Score)$/",$key,$cap);
$projectName=str_replace(","," ",$cap[1]);
if(preg_match("/Pos/",$key)){
$$key=(strlen($val)>10?substr($val,0,10):$val);
$delta=$key."Delta";
$$delta=($val - $teamOld->{$key});
$$delta=(strlen($$delta)>5?substr($$delta,0,5):$$delta);
if($projectName!=="Overall"){
if(!in_array($projectName,array("Physical Science","Bio/Med Science","Mathematics","Miscellaneous"))){
$projects[$projectName]["position"]=$$key;
$projects[$projectName]["position delta"]=$$delta*1;
}else{
$subsections[$projectName]["position"]=$$key;
$subsections[$projectName]["position delta"]=$$delta*1;
}
}
}elseif(preg_match("/Score/",$key)){
$$key=(strlen($val)>10?substr($val,0,10):$val);
$delta=$key."Delta";
$$delta=($val - $teamOld->{$key});
$$delta=(strlen($$delta)>9?substr($$delta,0,9):$$delta);
if($projectName!=="Overall"){
if(!in_array($projectName,array("Physical Science","Bio/Med Science","Mathematics","Miscellaneous"))){
$projects[$projectName]["score"]=$$key;
$projects[$projectName]["score delta"]=$$delta;
}else{
$subsections[$projectName]["score"]=$$key;
$subsections[$projectName]["score delta"]=$$delta;
}
}
}
}
$sort=array();
foreach($projects as $key=>$row){
$sort[$key]=$row["score"];
}
array_multisort($sort,SORT_DESC,$projects);
$lastupdated=round($hours,2).' hours ago';
$y=35;
foreach($projects as $name=>$project){
imagettftext($template,10,0,5,$y,$black,$font,$name);
imagettftext($template,10,0,149,$y,$black,$font,$project['position']);
imagettftext($template,10,0,216,$y,$black,$font,$project['position delta']*-1);
imagettftext($template,10,0,257,$y,$black,$font,$project['score']);
imagettftext($template,10,0,331,$y,$black,$font,$project['score delta']);
$y+=20;
}
$y=655;
foreach($subsections as $name=>$subsection){
imagettftext($template,10,0,5,$y,$black,$font,$name);
imagettftext($template,10,0,149,$y,$black,$font,$subsection['position']);
imagettftext($template,10,0,216,$y,$black,$font,$subsection['position delta']*-1);
imagettftext($template,10,0,257,$y,$black,$font,$subsection['score']);
imagettftext($template,10,0,331,$y,$black,$font,$subsection['score delta']);
$y+=20;
}
imagettftext($template,10,0,149,735,$black,$font,$team->{'OverallPos'});
imagettftext($template,10,0,216,735,$black,$font,$OverallPosDelta*-1);
imagettftext($template,10,0,257,735,$black,$font,$OverallScore);
imagettftext($template,10,0,331,735,$black,$font,$OverallScoreDelta);
imagettftext($template,10,0,149,755,$black,$font,$lastupdated);
imagepng($template);
?>
And here is what the data looks like when it is saved:
"{\"teamName\":{\"Folding#HomePos\":\"51\",\"Folding#HomeScore\":\"9994.405407\"},\"date\":\"2014-03-14 11:00:00\"}"
I've omitted most of the data because it just makes things excessively long, and it helps to see the format. Now the reason why its an unexpected output is because I didn't expect trailing slashes to be in it. The older version of this code would output like this:
{"teamName":{"Asteroids#HomePos":"192","Asteroids#HomeScore":"7647.783251"},"date":"2014-03-14 11:00:00"}
So the expected behaviour is to to gather the data from the aforementioned rows in each tab delimited text file, copy the old data into the 'old' data file (vaultDataold), save the new data into the 'current' data file (vaultData), and then display the data from the 'current' file in a dynamic image, along with performing a 'new' minus 'old' calculation on the two files to show the change since the previous day.
Most of this code should work, as I've had it working before in a different way. The issue likely lies somewhere with gathering the row data and saving it, most probably the latter. I'm guessing the slashes are causing the issue.
Turns out that the cause was twofold. Firstly, in my function, I was JSON encoding something that had already been encoded, so when the second file was saved, it appeared as shown in my question. To fix that, I did this:
$final_json['date']=date("Y-m-d G:i:s",strtotime("11:00"));
$encode_json=json_encode($final_json);
file_put_contents("$root/scripts/vaultData.js",$encode_json);
return $final_json;
In addition, as pointed out by another in the comments, I had to add $root to my function, and again within it.

Instagram Real time API - PHP - Unable to get POST Update

I'm trying to connect with the instagram API, the connection works fine and I am receiving the updates just as described in the API documentation, the issue is that I cannot access to the data send to my callback function.
According to the doc
When someone posts a new photo and it triggers an update of one of your subscriptions, we make a POST request to the callback URL that you defined in the subscription
This is my code :
// check if we have a security challenge
if (isset ($_GET['hub_challenge']))
echo $_GET['hub_challenge'];
else // This is an update
{
// read the content of $_POST
$myString = file_get_contents('php://input');
$answer = json_decode($myString);
// This is not working starting from here
$id = $answer->{'object_id'};
$api = 'https://api.instagram.com/v1/locations/'.$id.'/media/recent?client_secret='.INSTA_CLI_SECRET.'&client_id='.INSTA_CLI_ID;
$response = get_curl($api); //change request path to pull different photos
$images = array();
if($response){
$decode = json_decode($response);
foreach($decode->{'data'} as $item){
// do something with the data here
}
}
}
Displaying the $myString variable I have this result, don't know why it is not decoded to json :(
[{"changed_aspect": "media", "subscription_id": 2468174, "object":
"geography", "object_id": "1518250", "time": 1350044500}]
the get_curl function is working fine when I hardcode my $id.
I guess something is wrong with my $myString, unfortunately the $_POST cvariable is not populated, Any idea what I am missing ?
Looking at the example JSON response included in your question, I can conclude that the object you are trying to talk with is wrapped in an array (hence the [ and ] around it in the JSON string).
You should access it using $answers[0]->object_id.
If that doesn't work, you can always use var_dump to check out the data in one of your variables.

Extract Data from a Website using PHP

I am trying to get PHP to extract the TOKEN (the uppercase one), USERID (uppercase), and the USER NAME (uppercase) from a web page with the following text.
{
"rsp":{
"stat":"ok",
"auth":{
"token":"**TOKEN**",
"perms":"read",
"user":{
"id":"**USERID**",
"username":"**USER NAME**",
"fullname":"**NAME OF USER**"
}
}
}
}
(This is from the RTM api, getting the authentication token of the user).
How would I go about doing this? Thanks!
EDIT:
how would i get task name "Buy Milk!" & the due date of the task"2011-02-28T.." using json_decode and php here? Thanks!
{
"rsp":{
"stat":"ok",
"tasks":{
"rev":"REV_NUMBER",
"list":{
"id":"ID_NUMBER",
"taskse­­ries":{
"id":"ID_NUMBER",
"created":"2010-11-16T00:01:50Z",
"modified":"2011-02-28T05:09:36Z",
"name":"Buy Milk!",
"source":"js",
"url":"",
"location_id":"",
"rrule":{
"every":"1",
"$t":"FREQ=W­­EEKLY;INTERVAL=1"
},
"tags":[
],
"participants":[
],
"notes":[
],
"task":{
"id":"ID_NUMBER" ­­,
"due":"2011-02-28T05:00:00Z",
"has_due_time":"0",
"added":"2011-02-21T05:04:49Z",
"completed":"",
"deleted":"",
"priority":"2",
"postponed":"0",
"estima­­te":""
}
}
}
}
}
}
As Delan suggested, use json_decode. Here is an example of how you would use json_decode to extract the information you require.
// your json string
$string = '{"rsp":{"stat":"ok","auth":{"token":"**TOKEN**","perms":"read","user":{"id":"**USERID**","username":"**USER NAME**","fullname":"**NAME OF USER**"}}}}';
// parse json string to an array
$array = json_decode($string, true);
// auth token
echo $array['rsp']['auth']['token'];
// user details
echo $array['rsp']['auth']['user']['id'];
echo $array['rsp']['auth']['user']['username'];
echo $array['rsp']['auth']['user']['fullname'];
UPDATE I've updated the code to use json_decode's $assoc parameter to convert from an object to an assoc array.
ANOTHER UPDATE To answer your updated question..
how would i get task name "Buy Milk!" & the due date of the task"2011-02-28T.." using json_decode and php here? Thanks!
This code would work to get the values that you want.
//string(9) "Buy Milk!"
echo $array['rsp']['tasks']['list']['taskseries']['name'];
// string(20) "2011-02-28T05:00:00Z"
echo $array['rsp']['tasks']['list']['taskseries']['task']['due'];
This code isn't ideal, but it gets the job done for you.
If the string is JSON, json_decode in PHP will do the trick. It's was implemented in PHP 5.2.0.
http://www.php.net/manual/en/function.json-decode.php

Categories