How to add object inside object in php? - php

I am currently having problem creating a json response as I don't use PHP that much but can anyone help me create json like below:
{
"set_attributes":
{
"apikey": "some value",
},
"block_names": ["getdata"],
"type": "show_block",
"title": "go"
}
Here's my code:
$response = array();
$response['block_names'] = array();
$response['block_names'] = "getdata";
$response['type'] = "show_block";
$response['title'] = "go";
if ($db->studentLogin($username, $password)) {
$student = $db->getStudent($username);
$temp = array();
$temp['apikey'] = $student['api_key'];
$response['set_attributes'] = $temp['apikey'];
} else {
$temp = array();
$response['messages'] = array();
$temp['text'] = "Invalid username or password";
array_push($response['messages'],$temp);
}
echoResponse(200, $response);
It shows like this:
{
"block_names": "getdata",
"type": "show_block",
"title": "go",
"set_attributes": "f74911b29778adea86aa24d5ce85ff58"
}
But I want to add apikey = "f74911b29778adea86aa24d5ce85ff58" inside set_attributes and [] outside block_names just like obove. how can I do that?

try this:
$response['block_names'] = array("getdata");
...
$response['set_attributes'] = new \stdClass();
$response['set_attributes']->apikey = 'some_api_key';
https://3v4l.org/GDMKT#output

Related

Edit JSON file using PHP

I'm trying to edit a JSON file using php, I've set up a little ReactJS app has form elements.
My JSON is as follows
[
{
"id": 1,
"Client": "client 1",
"Project": "project 1",
"StartDate": "2018\/11\/02 16:57:35",
"CompletedDate": "",
"projectUrl": "project-1"
},
{
"id": 2,
"Client": "client 2",
"Project": "project 2",
"StartDate": "2018\/11\/02 16:57:35",
"CompletedDate": "",
"projectUrl": "project-2"
},
{
"id": 3,
"Client": "client 3",
"Project": "project 3",
"StartDate": "2018\/11\/02 16:57:35",
"CompletedDate": "",
"projectUrl": "project-3"
}
]
So far i have code to create a new "project" at the end of the file. My PHP is as follows
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
try {
$clientName = $_POST['clientName'];
$ProjectName = $_POST['projectName'];
$url = strtolower($_POST['url']);
$date = date('Y/m/d H:i:s');
$message = "";
$url = '../json/projects.json';
if( file_exists($url) )
if(file_exists('../json/projects.json'))
{
$current_data = file_get_contents('../json/projects.json');
$array_data = json_decode($current_data, true);
$extra = array(
'id' => count($array_data) + 1,
'Client' => $clientName,
'Project' => $ProjectName,
'StartDate' => $date,
'CompletedDate' => "",
'projectUrl' => $projectFileName + ".json"
);
$array_data[] = $extra;
$final_data = json_encode($array_data, JSON_PRETTY_PRINT);
if(file_put_contents('../json/projects.json', $final_data))
{
$message = "sent";
}
else
{
$message = "notSent";
}
}
else
{
$message = "jsonFileNotFound";
}
$response = $message;
} catch (Exception $e) {
$response = $e->getMessage();
}
echo $response;
}
What i can figure out is how to edit lets say "CompletedDate" value to todays date with a click of the button.
I have an hidden input field on my page that has the project ID in, so what I'm after is helping getting that id, matching it to the JSON, then editing the completed date that matches the ID.
This PHP will fire using ajax so i can pass the ID pretty easy.
Using similar code to what you already use, you can update the relevant data by using the ID as the index into the decoded JSON file. As ID 1 will be the [0] element of the array, update the [$id-1] element with the date...
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
try {
$id = 2; // Fetch as appropriate
$date = date('Y/m/d H:i:s');
$url = '../json/projects.json';
if( file_exists($url) )
{
$current_data = file_get_contents($url);
$array_data = json_decode($current_data, true);
$array_data[$id-1]['CompletedDate'] = $date;
$final_data = json_encode($array_data, JSON_PRETTY_PRINT);
if(file_put_contents($url, $final_data))
{
$message = "updated";
}
else
{
$message = "notUpdated";
}
}
else
{
$message = "jsonFileNotFound";
}
$response = $message;
} catch (Exception $e) {
$response = $e->getMessage();
}
echo $response;
}
You may need to tweak some of the bits - especially how the ID is picked up ($_GET?) and any messages you want.
I've also updated the code to make more consistent use of $url as opposed to hard coding it in a few places.

Using PHP to find specific entry in JSON URL response

I am trying to find out whether a user is part of a Steam group. To do this, I'm using Steam's Web API, and using URL:
https://api.steampowered.com/ISteamUser/GetUserGroupList/v1/?key=APIKEYHERE&steamid=STEAMID64HERE
To get a JSON response of all groups that a user is part of.
Now I want to find out if they're part of my specific group with ID: 1111111 using PHP.
How would one do that? Currently I have the code being decoded like so:
$groupid = "1111111";
$url = "https://api.steampowered.com/ISteamUser/GetUserGroupList/v1/?key=APIKEYHERE&steamid=STEAMID64HERE";
$result = file_get_contents($url);
// Will dump a beauty json :)
$pretty = json_decode($result, true);
This makes the $pretty variable contain the entire JSON response.
How would I use PHP to find the group ID in a response that looked like this?
{
"response": {
"success": true,
"groups": [
{
"gid": "4458711"
},
{
"gid": "9538146"
},
{
"gid": "11683421"
},
{
"gid": "24781197"
},
{
"gid": "25160263"
},
{
"gid": "26301716"
},
{
"gid": "29202157"
},
{
"gid": "1111111"
}
]
}
}
Can't figure it out.
Any help? :)
Use the below code to check whether user is exist in the response or not
$groupid = "1111111";
$is_exists = false;
$url = "https://api.steampowered.com/ISteamUser/GetUserGroupList/v1/?key=APIKEYHERE&steamid=STEAMID64HERE";
$result = file_get_contents($url);
// Will dump a beauty json :)
$pretty = json_decode($result, true);
foreach ($pretty['response']['groups'] as $key => $value) {
if($value['gid'] == $groupid) {
$is_exists = true;
break;
}
}
// check is_exists
Check that above variable $is_exists for true or false
$groupid = "1111111";
$url = "https://api.steampowered.com/ISteamUser/GetUserGroupList /v1/?key=APIKEYHERE&steamid=STEAMID64HERE";
$result = file_get_contents($url);
// Will dump a beauty json :)
$pretty = json_decode($result);
$s = $pretty->response->groups;
foreach($s as $value)
{
if((int) $groupid == $value->gid)
{
echo "Found";
}else
{
echo "Not found";
}
}

How to get json array and insert in the database. php

I have a table on an Invitation. I am passing the data in json format from postman.
I want to send many invitations at a time. So I want to insert multiple invitations.
How can I do this?
I have created a single invitation.
Invitaion :
class Invitation
{
private $sender_id,$date,$invitee_no,$status;
function Invitation($sender_id,$date,$invitee_no,$status)
{
$this->sender_id = $sender_id;
$this->date= $date;
$this->invitee_no = $invitee_no;
$this->status = $status;
}
function sendInvite()
{
$database = new Database(ContactsConstants::DBHOST,ContactsConstants::DBUSER,ContactsConstants::DBPASS,ContactsConstants::DBNAME);
$dbConnection = $database->getDB();
$stmt = $dbConnection->prepare("select * from Invitation where invitee_no =?");
$stmt->execute(array($this->invitee_no));
$rows = $stmt->rowCount();
if($rows > 0)
{
$response = array("status"=>-3,"message"=>"Invitation exists.");
return $response;
}
$stmt = $dbConnection->prepare("insert into Invitation(date,invitee_no,status) values(?,?,?)");
$stmt->execute(array($this->date, $this->invitee_no, $this->status));
$rows = $stmt->rowCount();
$Id = $dbConnection->lastInsertId();
$stmt = $dbConnection->prepare("select * from Invitation where sender_id=?");
$stmt->execute(array($Id));
$invitation = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($rows < 1) {
$response = array("status" => -1, "message" => "Failed to send Invitation., unknown reason");
return $response;
} else {
$response = array("status" => 1, "message" => "Invitation sent.", "Invitation:" => $invitation);
return $response;
}
}
}
sendInvite.php
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
ini_set('display_errors', '1');
require 'Invitation.php';
$jsonText = file_get_contents('php://input');
if(empty($jsonText))
{
$response = array("status"=>-2,"message"=>"Empty request");
die(json_encode($response));
}
$json = json_decode($jsonText);
$date= $json -> date;
$invitee_no = $json -> invitee_no;
$status = $json -> status;
$invitation = new Invitation("",$date,$invitee_no,$status);
$response = $invitation->sendInvite();
echo(json_encode($response));
?>
Input from postman:
{
"date" : "12/08/2016",
"invitee_no" : "5258",
"status" : "1"
}
Output:
{
"status": 1,
"message": "Invitation sent.",
"Invitation:": [
{
"sender_id": "29",
"date": "12/08/2016",
"invitee_no": "5259",
"status": "1"
}
]
}
EDIT:
In Send Invite() function:
if ($rows < 1) {
$response = array("status" => -1, "message" => "Failed to send Invitation., unknown reason");
echo(json_encode($response));
} else {
$response = array("status" => 1, "message" => "Invitation sent.", "Invitation:" => $invitation);
echo(json_encode($response));
}
In senInvite.php file :
foreach ($json as $jsn) {
foreach($jsn as $j)
{
$date= $j -> date;
$invitee_no = $j -> invitee_no;
$status = $j -> status;
$invitation = new Invitation("",$date,$invitee_no,$status);
$response = $invitation->sendInvite();
var_dump($response);
die();
echo(json_encode($response));
}
}
var dump:
{"status":-3,"message":"Invitation exists.","invitee_no":"5856"}array(3) {
["status"]=>
int(-3)
["message"]=>
string(18) "Invitation exists."
["invitee_no"]=>
string(4) "5856"
}
Gives syntax error: unexpeted 'S'
I want to accept this as json array and insert into the table all the records.
Can anyone help please? Thank you..
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
ini_set('display_errors', '1');
require 'Invitation.php';
$jsonText = file_get_contents('php://input');
if(empty($jsonText))
{
$response = array("status"=>-2,"message"=>"Empty request");
die(json_encode($response));
}
$response = array();
$json = json_decode($jsonText);
foreach ($json as $jsn) {
foreach($jsn as $j)
{
$date= $j -> date;
$invitee_no = $j -> invitee_no;
$status = $j -> status;
$invitation = new Invitation("",$date,$invitee_no,$status);
$response[] = $invitation->sendInvite();
}
}
echo(json_encode($response));
?>
I have used foreach for array.

PHP Parse Json from HTTP response & Foreach Iterate Array

There are several focused questions on this topic but after trying them all I felt the need to seek out help. I am using Sendgrid, their webhook sends a json response and for some reason I have been unable to figure out how to integrate with our CRM.
Update: 12/3/2015 # 1:01pm - I got some code to work (probably not the most efficient but it works) see below.
Example JSON from Sendgrid being sent:
[
{
"sg_message_id":"sendgrid_internal_message_id",
"email": "john.doe#sendgrid.com",
"timestamp": 1337197600,
"smtp-id": "<4FB4041F.6080505#sendgrid.com>",
"event": "spamreport"
},
{
"sg_message_id":"sendgrid_internal_message_id",
"email": "john.doe#sendgrid.com",
"timestamp": 1337966815,
"category": "newuser",
"event": "bounce",
"url": "https://sendgrid.com"
},
{
"sg_message_id":"sendgrid_internal_message_id",
"email": "john.doe#sendgrid.com",
"timestamp": 1337969592,
"smtp-id": "<20120525181309.C1A9B40405B3#Example-Mac.local>",
"event": "unsubscribe",
"asm_group_id": 42
}
]
The issue I am running into is that each array in the JSON pertains to a particular event. For example "Spam", or "Bounced" or "Unsubscribe". I've set it up so that only those three events are sent. However there is a possibility that someone will bounce first, then get it, then hit spam, then hit unsubscribe.
The simplest solution for this (disregarding a heirarchy system) is to have each of these events pass along to a specific field in our CRM. For example if the event = spam, then it would fill $spam with "spam". However if it is not present it should do nothing.
One last note, I have to pass a header across so that Sendgrid will stop spamming the script. Also I am not a coder, or programmer, I have just picked up a few things over the last few months.
My Script that Isn't Working:
<?php
$data = file_get_contents("php://input");
$events = json_decode($data, true);
require_once('Infusionsoft/infusionsoft.php');
$contact = new Infusionsoft_Contact();
$custom = array(
'_SGBounce',
'_SGSpam',
'_SGUnsub'
);
$contact->addCustomFields($custom);
if (is_array($events) || $events instanceof Traversable) {
foreach ($events as $event) {
$email = $event['email'];
if($event['event'] === 'bounce') {
$bounce = 'bounce';
} elseif ($event['event'] === 'spamreport') {
$spam = 'spam';
} elseif ($event['event'] === 'unsubscribe') {
$unsub = 'unsubscribe';
} else {
die echo header("HTTP/1.1 200 OK");
}
process_event($event);
}}
if (empty($email)) {
die echo header("HTTP/1.1 200 OK");
} else {
$contact->Email = $email;
$contact->_SGBounce = $bounce;
$contact->_SGSpam = $spam;
$contact->_SGUnsub = $unsub;
$contact->save();
}
header("HTTP/1.1 200 OK");
?>
I also have a script I am using that writes to a file, just to test and see if I can get the correct events to write. However I have been unsuccessful to get it to iterate past the first array. I've tried nesting the foreach() in another foreach() with a key => value solution posted in another answer here. However that was also a dead end.
Any tips, help, and guidance... would be greatly appreciated.
Update: Working Code Below (in case this helps someone)
<?php
$data = file_get_contents("php://input");
$events = json_decode($data, true);
require_once('Infusionsoft/infusionsoft.php');
$contact = new Infusionsoft_Contact();
$custom = array(
'_SendGrid',
);
$contact->addCustomFields($custom);
$emails = array();
$em = '';
if (is_array($events) || $events instanceof Traversable) {
foreach ($events as $event) {
$email = $event['email'];
$em = $email;
if($event['event'] === 'unsubscribe') {
$event = 'unsubscribe';
$unsubscribe = 'unsubscribe';
} elseif($event['event'] === 'spamreport') {
$event = 'spam';
$spam = 'spam';
} elseif($event['event'] === 'bounce') {
$event = 'bounce';
$bounce = 'bounce';
} else {
continue;
}
$default = array(
'bounce' => false,
'spam' => false,
'unsubscribe' => false
);
if(!is_null($event)) {
if(array_key_exists($email, $emails)) {
$entry = $emails[$email];
} else {
$entry = $default;
}
switch($event) {
case "bounce":
$entry['bounce'] = true;
break;
case "spam":
$entry['spam'] = true;
break;
case "unsubscribe":
$entry['unsubscribe'] = true;
break;
}
}
}}
if($unsubscribe === 'unsubscribe'){
$param = 'unsubscribe';
} elseif($spam === 'spam'){
$param = 'spam';
} elseif($bounce === 'bounce'){
$param = 'bounce';
} else {
echo header("HTTP/1.1 200 OK");
}
$contact->Email = $em;
$contact->_SendGrid = $param;
$contact->save();
header("HTTP/1.1 200 OK");
?>
What you could do, is process it like this;
$emails = array();
foreach ($events as $event) {
$email = $event['email'];
if($event['event'] === 'bounce') {
$event = 'bounce';
} elseif ($event['event'] === 'spamreport') {
$event = 'spam';
} elseif ($event['event'] === 'unsubscribe') {
$event = 'unsubscribe';
} else {
continue;
}
// Set defaults
$default = array(
'bounce' => false,
'spam' => false,
'unsubscribe' => false
);
if(!is_null($event)) {
if(array_key_exists($email, $emails)) {
$entry = $emails[$email];
} else {
$entry = $default;
}
switch($event) {
case "bounce":
$entry['bounce'] = true;
break;
case "spam":
$entry['spam'] = true;
break;
case "unsubscribe":
$entry['unsubscribe'] = true;
break;
}
}
}
Then you'd end up with a list of emails that are their own array with boolean values for keys bounce, spam and unsubscribe. You could do a loop over that array to save the data.

Creating default object from empty value ( stdClass? )

The script run good, but only when I fetching out the groups of the user, it's says:
SteamUser.php (132): Creating default object from empty value
function getProfileData() {
//Set Base URL for the query:
if(empty($this->vanityURL)) {
$base = "http://steamcommunity.com/profiles/{$this->userID}/?xml=1";
} else {
$base = "http://steamcommunity.com/id/{$this->vanityURL}/?xml=1";
}
try {
$content = SteamUtility::fetchURL($base);
if ($content) {
$parsedData = new SimpleXMLElement($content);
} else {
return null;
}
} catch (Exception $e) {
//echo "Whoops! Something went wrong!\n\nException Info:\n" . $e . "\n\n";
return null;
}
if(!empty($parsedData)) {
$this->steamID64 = (string)$parsedData->steamID64;
$this->steamID = (string)$parsedData->steamID;
$this->stateMessage = (string)$parsedData->stateMessage;
$this->visibilityState = (int)$parsedData->visibilityState;
$this->privacyState = (string)$parsedData->privacyState;
$this->avatarIcon = (string)$parsedData->avatarIcon;
$this->avatarMedium = (string)$parsedData->avatarMedium;
$this->avatarFull = (string)$parsedData->avatarFull;
$this->vacBanned = (int)$parsedData->vacBanned;
$this->tradeBanState = (string)$parsedData->tradeBanState;
$this->isLimitedAccount = (string)$parsedData->isLimitedAccount;
$this->onlineState = (string)$parsedData->onlineState;
$this->inGameServerIP = (string)$parsedData->inGameServerIP;
//If their account is public, get that info:
if($this->privacyState == "public") {
$this->customURL = (string)$parsedData->customURL;
$this->memberSince = (string)$parsedData->memberSince;
$this->steamRating = (float)$parsedData->steamRating;
$this->hoursPlayed2Wk = (float)$parsedData->hoursPlayed2Wk;
$this->headline = (string)$parsedData->headline;
$this->location = (string)$parsedData->location;
$this->realname = (string)$parsedData->realname;
$this->summary = (string)$parsedData->summary;
}
//If they're in a game, grab that info:
if($this->onlineState == "in-game") {
$this->inGameInfo = array();
$this->inGameInfo["gameName"] = (string)$parsedData->inGameInfo->gameName;
$this->inGameInfo["gameLink"] = (string)$parsedData->inGameInfo->gameLink;
$this->inGameInfo["gameIcon"] = (string)$parsedData->inGameInfo->gameIcon;
$this->inGameInfo["gameLogo"] = (string)$parsedData->inGameInfo->gameLogo;
$this->inGameInfo["gameLogoSmall"] = (string)$parsedData->inGameInfo->gameLogoSmall;
}
//Any weblinks listed in their profile:
if(!empty($parsedData->weblinks)) {
$this->weblinks = array();
$i = 0;
foreach ($parsedData->weblinks->weblink as $weblink) {
$this->weblinks[$i]->title = (string)$weblink->title;
$this->weblinks[$i]->link = (string)$weblink->link;
$i++;
}
}
if(!empty($parsedData->groups)) {
$this->groups = array();
$i = 0;
foreach ($parsedData->groups->group as $group) {
$this->groups[$i]->groupID64 = (string)$group->groupID64; // row 132 in script
$this->groups[$i]->groupName = (string)$group->groupName;
$this->groups[$i]->groupURL = (string)$group->groupURL;
$this->groups[$i]->headline = (string)$group->headline;
$this->groups[$i]->summary = (string)$group->summary;
$this->groups[$i]->avatarIcon = (string)$group->avatarIcon;
$this->groups[$i]->avatarMedium = (string)$group->avatarMedium;
$this->groups[$i]->avatarFull = (string)$group->avatarFull;
$this->groups[$i]->memberCount = (string)$group->memberCount;
$this->groups[$i]->membersInChat = (string)$group->membersInChat;
$this->groups[$i]->membersInGame = (string)$group->membersInGame;
$this->groups[$i]->membersOnline = (string)$group->membersOnline;
$i++;
}
}
}
}
.
.
.
I already tried to using associative arrays, but didn't work; maybe with doing it all new. -_-
So, I can't set error_reporting(0) or ini_set at all.
I also used new stdClass() as a try. But I didn't get this running too.
You create an array.
$this->groups = array();
But in this array you donot create any object. You just use this array's elements (thoes are not initialized) as objects. You should add this line before your 132. row.
$this->groups[$i] = new Group();
Or something similar.
If you do not have Group class you should try
$this->groups[$i] = new stdClass();

Categories