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');
}
Related
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.
I am using Block.io Web Hooks. It says that the notification service requires to communicate through POST requests. It also stated that all notification events will use the following JSON objects structure:
{
"notification_id" : "...", // a unique identifier issued when you created the notification
"delivery_attempt" : 1, // number of times we've tried deliverying this object
"type" : "...", // the type of notification, helps you understand the data sent below
"data" : {
... // the notification data
},
"created_at" : 1426104819 // timestamp of when we created this notification
}
I have provided my callback URL and I saw there is row inserted into my database but the value is blank. Yes I know that my code will insert blank but when I trigger the API it is also insert blank.
<?php
$post = '';
foreach($_POST as $k => $v){
$post .= $k.'='.$v.'&';
}
// save data into database
?>
The webhook returns json and this will not be parsed to the $_POST array by PHP.
Instead, you need to get the string from:
file_get_contents('php://input')
This you can parse yourself. To get an array:
$array = json_decode(file_get_contents('php://input'), true);
I have a file called data.txt in the public path , it has this
{"data":[{"name": "Jack", "age": 13},{"name": "Mary", "age": 15}]}
and I want to read these data and also return the age for both Jack and Mary,
I know that I can read the file using the decode_json(file_get_contents) but I have no clue how to fetch the data and return specific records from it.
Any help is much appreciated !
You can load the file and decode the content with:
$content = json_decode(file_get_contents($path), true);
This will give you the associative array that contains your JSON content.
You can access data in user objects like that:
$userData = $content['data']; // content of "data" field
$jackData = $userData[0]; // first object in "data" array - Jack
$jackName = $jackData['name']; // Jack's name
I'm getting this kind of response from instagram server.
{
"meta": {
"code": 200
},
"data": {
...
},
"pagination": {
"next_url": "...",
"next_max_id": "13872296"
}
}
How do I get the "data" - part? I've tried to json decoding in PHP like:
//$userfeed is giving me something like above.
$tried_this = json_decode($userfeed['meta']);
but $userfeed and $tried_this seems to be the same.
UPDATE
Down below is the REAL data...
I've left out the access token, but otherwise it's correct. This is just a part of it, but I hope you get the picture....
{"pagination":{"next_url":"https://api.instagram.com/v1/users/3/media/recent?access_token=blablabla\u0026max_id=622063574553989866_3","next_max_id":"622063574553989866_3"},"meta":{"code":200},"data":[{"attribution":null,"tags":[],"type":"image","location":{"latitude":21.367158921,"name":"Pali
Lookout","longitude":-157.79304912,"id":60507},"comments":{"count":313,"data":[{"created_time":"1401835727","text":"Can
you give me a shout
out","from":{"username":"nick_putukian1","profile_picture":"http://images.ak.instagram.com/profiles/profile_1370615750_75sq_1401835573.jpg","id":"1370615750","full_name":"Nicholas
Putukian"},"id":"734973811849433422"},{"created_time":"1401836165","text":"I
only have one
follower","from":{"username":"nick_putukian1","profile_picture":"http://images.ak.instagram.com/profiles/profile_1370615750_75sq_1401835573.jpg","id":"1370615750","full_name":"Nicholas
Putukian"},"id":"734977485287985692"},{"created_time":"1401837312","text":"Dear
#kevin could u please add share feature on IG? So users don't have to
screenshoot a foto first if we want to share it.
Thanks.","from":{"username":"natalia.igaa","profile_picture":"http://images.ak.instagram.com/profiles/profile_1003500786_75sq_1401603184.jpg","id":"1003500786","full_name":"Ayu
Natalia"},"id":"734987110351638699"},{"created_time":"1401837882","text":"HI
KEVIN","from":{"username":"gildathegriffon","profile_picture":"http://images.ak.instagram.com/profiles/profile_320785380_75sq_1401742420.jpg","id":"320785380","full_name":"Doivid"},"id":"734991884560110057"},{"created_time":"1401838561","text":"\ud83d\ude02\ud83d\ude02\ud83c\udf42\ud83d\udc9
Forgive me for not giving you a "readable" var_dump, but for some reason the var_dump on a specific server I'm trying on doesn't make it readable as expected.
$data = json_decode($userfeed, true);
var_dump($data['data']);
is returning NULL
Assuming, a valid JSON string, you would do:
$data = json_decode($json_string, true);
var_dump($data['data']);
Lets assume that you have provided access_token, than following syntax will meet your requirements
$url = "https://api.instagram.com/v1/users/3/media/recent/?access_token=ACCESS-TOKEN";
$content = file_get_contents($url);
$data = json_decode($content, true);
var_dump($data['data']);
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.