I'm messing about with FB Messenger and trying to send a 'list' back, this has to be created with a mySQL lookup and loop.
The correct JSON to send back is defined on Facebook Developers here.
What I cannot understand is how with PHP I create the 'header' and 'footer' of the object, I have made a loop to put the main content into an array using my database results:
$messagePayload = array();
while($row = $result->fetch_assoc()) {
$messagePayloadC = array();
$messagePayloadC['title'] = $row['Name'].";
$messagePayloadC['item_url'] = $row['link'];
$messagePayloadC['image_url'] = $row['Image'];
$messagePayloadC['subtitle'] = "$".$row['Price'].";
$messagePayloadC['buttons']['type'] = "web_url";
$messagePayloadC['buttons']['url'] = $row['link'];
$messagePayloadC['buttons']['title'] = "Go!";
$messagePayload[] = $messagePayloadC;
}
echo var_dump(json_encode($messagePayload))."<p>";
What I need to do is add all of the missing peices at the start and end. The output of my array gives:
{"title":"My Television","item_url":"https:\/\/www.google.com\/","image_url":"product-image.jpg","subtitle":"$5","buttons":{"type":"web_url","url":"https:\/\/www.google.com\/","title":"Go!"}}
The missing header for example is:
"attachment": {
"type": "template",
"payload": {
"template_type": "list",
"top_element_style": "compact",
"elements": [
Am I going about this in the wrong way ?
Related
For a site I'm working on, a user has the option to input exercise data and it is saved to a JSON file in an array:
{
"Email": "chandlerbing#centralperk.com",
"ExerciseType": "Running",
"DistanceTravelled": "35",
},
But what I want it to do is to be able to save it in a multidimensional array so multiple records can be put in for one user.
Example:
{
"chandlerbing#centralperk.com"
{
"ExerciseType": "Running",
"DistanceTravelled": "35",
}
}
That way multiple records for the user are saved under one primary object to make it easier to access later. However I've never used multi-dimensional arrays before so I can't figure out how to modify my code to get this to work.
// Save data
$file = ('data.json');
$arr = array();
$new_userstats = array (
'Email' => $email,
'ExerciseType' => $exerciseType,
'DistanceTravelled' => $distance
);
$jsondata = file_get_contents($file);
$arr_data = json_decode($jsondata, true);
array_push($arr_data, $new_userstats);
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents($file,$jsondata);
If Email is the attribute to uniquely identify a user. It would be great to keep this as key of our array to easily find
and add a new data to existing file.
Now the format we would be storing in file looks like
{
"chandlerbing#centralperk.com" : [
{
"ExerciseType": "Running",
"DistanceTravelled": "35",
},
{
"ExerciseType": "Jogging",
"DistanceTravelled": "13",
},
],
"test#centralperk.com" : [
{
"ExerciseType": "Running",
"DistanceTravelled": "11",
},
]
}
Now how to add new data to this file would be in following way.
// Fetch existing data
$strFile = 'data.json';
$arrExistingData = json_decode(file_get_contents($strFile), true);
// Add new data to existing data, new data would contain and object in following way
$arrNewData = [
'ExerciseType' => $exerciseType,
'DistanceTravelled' => $distance
];
$arrExistingData[$email][] = $arrNewData;
// Save data back to file, avoid JSON_PRETTY_PRINT to reduce the file size.
file_put_contents($strFile, json_encode($arrExistingData));
Try:
$new_userstats = array (
$email => array (
'ExerciseType' => $exerciseType,
'DistanceTravelled' => $distance
)
);
My json file like:
{"c_d0_source": "AS-IISNRL",
"num_of_records": 4921,
"source": "last-all-airbox by IIS-NRL",
"version": "2020-05-10T17:01:36Z",
"descriptions": {"URL": "https://pm25.lass-net.org/data/description.json",
"c_d0_method": "method/days/distance(km)",
"c_d0": "calibration PM2.5 (ug/m3)"},
"feeds": [{"c_d0_method": "BRR/14/10.74",
"gps_lat": 24.37755,
"gps_num": 9.0, "s_d1": 0.0},
, {"c_d0_method": "BRR/14/10.74",
"gps_lat": 24.34755,
"gps_num": 9.0, "s_d1": 0.0}]}
I want to get all the information of "feeds" in "descriptions".
This is my php, and
my information is from api :
<?php
$fp = gzopen("https://pm25.lass-net.org/data/last-all-airbox.json.gz", "r");
if ($fp){
$data = array();
$arr =" ";
$lines = gzfile('https://pm25.lass-net.org/data/last-all-airbox.json.gz');
foreach ($lines as $line) {
$arr = $arr.$line;
}
$obj = json_decode($arr);
echo $obj->{"descriptions"}->{"feeds"};
}
else {
echo ("fail");
}
?>
The output is :
Undefined property: stdClass::$feeds .
How can I get this data?
Your JSON is not valid. When you fix the double comma issue, you'll notice that your "feeds" property is not inside the "description" property. It's on the same level, so use $obj->feeds directly.
Try to use "JSON formatter" to detect the problem next time.
I've php file and with this I want both set and get data. (Is it possible?).
This is my php file:
require_once 'GetAreaDB.php';
$latitudeFrom = $_POST['latitudeFrom'];
$longitudeFrom = $_POST['longitudeFrom'];
$maxDistance = $_POST['maxDistance'];
// These three values come from my swift app.
$getArea1 = new GetAreaDB();
$locals = $getArea1->getPositionByCoordinate($latitudeFrom,$longitudeFrom,$maxDistance);
$jsonArray = array();
foreach ($locals as $local) {
$jsonArray1 = array(
"id" => $local->getID(),
"json_local" => $local->getJSON()
);
array_push($jsonArray,$jsonArray1);
}
echo json_encode($jsonArray);
My idea is to create a php file that receives post parameters and then, on the base of these, it get other data.
How can I solve?
This question already has answers here:
Is there a JSON api based CMS that is hosted locally? [closed]
(1 answer)
Update JSON value if exists otherwise add it in PHP
(2 answers)
Closed 3 years ago.
I am running an app from AndroidHive which has feed.json which the app loads the content below from.
http://api.androidhive.info/feed/feed.json and this is the post url http://www.androidhive.info/2014/06/android-facebook-like-custom-listview-feed-using-volley/
{
"feed": [{
"id": 1,
"name": "National Geographic Channel",
"image": "A URL",
"status": "Science and etc"
And Cosmos is all about making science an experience.
","
profilePic ": "
A URL ","
timeStamp ": "
1403375851930 ","
url ": null
}]
}
the above is the default content am wondering how to i add more to this content from or using a php script. I would love to know how to do it because I noticed that most application source code created in www_androidhive_info uses .json to load content which is an alternative to webview
You can use json_decode() function to convert JSON string to object, add your variable, and then conver the object back to JSON
$obj = json_decode($json, true);
$obj->feed[0]->url = "google.com"
:
Load the JSON
Decode the JSON
Add your content
Encode to JSON
Send it to your app
Code:
<?php
function failure($reason) {
header('HTTP/1.1 500 Internal Server Error');
echo json_encode(['failure' => $reason]);
exit;
}
// 1. Load the JSON
$content = file_get_contents('http://api.androidhive.info/feed/feed.json');
if (!$content) {
return failure('Failed to load upstream JSON');
}
// 2. Decode the JSON
$decodedContent = json_decode($content, true);
if ($decodedContent === false) {
return failure('Failed to parse upstream JSON');
} elseif (empty($decodedContent)) {
return failure('Upstream JSON empty');
}
// 3. Add your content
$decodedContent['feed'][] = [
"id": 12,
"name": "An example name",
"image": "https://example.com/test_image.jpg",
"status": "Hello!",
"profilePic": "https://example.com/test_profile_pic.jpg",
"timeStamp" => time(),
"url" => "https://example.com"
];
// 4. Encode to JSON
$responseContent = json_encode($decodedContent);
// 5. Send it to your app
echo $responseContent;
Decode the JSON and make new function for changes then encode back.
<?php
$JsonVar = file_get_contents('http://api.androidhive.info/feed/feed.json');
$myjson = json_decode($JsonVar,true);
function Changes() {
$myjson->feed[2]->name = "FeedID2";
$myjson->feed[2]->id = "2";
$myjson->feed[2]->image = "link to image.png";
$myjson->feed[2]->status = "I am here.";
$myjson->feed[2]->profilePic = "link to image.png";
$myjson->feed[2]->timeStamp = time();
$myjson->feed[2]->url = 'http://url.com';
}
json_encode(Changes());
?>
I'm reading a json file using
$jsonStr = file_get_contents("connection.json");
$jsonParsed = json_decode($jsonStr,true);
and I want $jsonParsed to be a associative array like this:
$jsonParsed = { "SERVER" => "111.222.333.444" , "USER" => "edvaldo" , "PASSWORD" => "my_password_here", "DATABASE" => "my_database_here" };
What is the format of the JSON needed to do this?
I tried this
{
"SERVER": "111.222.333.444",
"USER": "edvaldo",
"PASSWORD": "my_password_here",
"DATABASE": "my_database_here"
}
but even with JSONLint saying this piece og JSON is valid, I can't get the result I need.
I'm not really very used to JSON and then I will appreciate a lot any help given.
EDITED:
This is the function I'm using:
private function set_mysql_parameters() {
$this->connectionParams = array();
$json_file = $this->system_paths["JSONDATA"] . "connection.json";
$json_mysql = file_get_contents($json_file);
$json_parsed = json_decode($json_file,true,250);
foreach($json_parsed as $key => $value) {
$this->connectionParams[$key] = $value;
}
}
My goal is to fill this array $this->connectionParams with data extracted from the JSON file.
I notice that you are trying to decode the filename instead of the content.
$json_file = $this->system_paths["JSONDATA"] . "connection.json";
$json_parsed = json_decode($json_file,true,250);
Shouldn't it be
$json_parsed = json_decode($json_mysql, true, 250);