hello i'm trying to save the values of a SimpleXMLElement to a $_SESSION but the values are entered as "SimpleXMLElement Object". code below:
$xml = new SimpleXMLElement($auth_info);
$_SESSION[userName] = $xml->profile->preferredUsername; (garfx)
$_SESSION[email] = $xml->profile->verifiedEmail;
$_SESSION[givenName] = $xml->profile->name->givenName;
$_SESSION[lastName] = $xml->profile->name->familyName;
results example
Array
(
[userName] => SimpleXMLElement Object
()
)
i would like
Array
(
[userName] => garfx
)
SimpleXML elements can be used as strings, but you need to "cast" them to a string.
Casting in PHP is done by prefixing the data type to a value,
so for example,
$foo = 1;
$bar = (string)$foo;
Would make $bar be a string containing the character "1".
The solution for the above would be:-
$xml = new SimpleXMLElement($auth_info);
$_SESSION[userName] = (string)$xml->profile->preferredUsername; // (garfx)
$_SESSION[email] = (string)$xml->profile->verifiedEmail;
$_SESSION[givenName] = (string)$xml->profile->name->givenName;
$_SESSION[lastName] = (string)$xml->profile->name->familyName;
Cast it as a (string)
$xml = new SimpleXMLElement($auth_info);
$_SESSION[userName] = (string)$xml->profile->preferredUsername;
$_SESSION[email] = (string)$xml->profile->verifiedEmail;
$_SESSION[givenName] = (string)$xml->profile->name->givenName;
$_SESSION[lastName] = (string) $xml->profile->name->familyName;
Related
So I want to get the saved database option and then update it with the API return and then save the option in the database again, but I'm having some issues.
So I have the following method:
public static function refresh_access_token(string $user_id, string $access_token): bool
{
if (!$authenticated_users = get_option('instagram_authenticated_users')) {
return false;
}
// The code for the cURL request is here (It's not needed for this question).
$array = json_decode($curl_exec);
foreach ($authenticated_users as $user) {
if ($user['user_id'] === (int) $user_id) {
$user['access_token'] = $array->access_token;
$user['access_token_expiration'] = time() + $array->expires_in;
$user['last_updated'] = (string) time();
}
}
return update_option('instagram_authenticated_users', $user);
}
The cURL response $array gives me the following:
$array = {stdClass} [3]
access_token = "IGQVJVV1YzUEdMb1lDajNZAcmRxakR3V0dkOXUyWHdtSGM0ZAHFYempkX0VHYVlKYTVYMkNxYVVpNVFuclZAlWVRsbmktNjN2cG1ISEJ4T2VJWUd0M2JBMGcyUlFXOWFlTjdEVDhKaEJB"
token_type = "bearer"
expires_in = {int} 5099901
Now within $authenticated_users, I have an array of arrays which outputs:
$authenticated_users = {array} [2]
[0] = {array} [5]
username = "semi_test1"
user_id = {int} 17841449642220098
access_token = "IGQVJWMDJnblBnUGMtMTVFa1NpUGdValNBVUZAyZAWM2OTdSSkRFdmNUbnVOQXJqeFhwbDVmT0c3aXJfamFYdnZANSlpXc3Mwc05PS0tMSzNsbXhES0tkTzNoOEY3RFRIb3dsblBiTXN3"
access_token_expiration = {int} 1651281005
last_updated = {int} 1646181108
[1] = {array} [5]
username = "semi_test2"
user_id = {int} 17841400835712753
access_token = "IGQVJVN3VOaUJrU2NzdGxWVTlwaXFLT2h1bnpFU3FKaEpOUGNPeWh2SkpjdHpnRXkyaGJ3NDZArXzJvRWFHdVRqZAEFfN0RodjV4cHQ2YTliSmhyVThUSjlCc1paLV9Fd2dqbzI1b25B"
access_token_expiration = {int} 1651281136
last_updated = {int} 1646181136
Now I'm looking at my $user_id param and using the foreach to compare them to the user_id inside an array, and if it matches, update the values inside the array and then update the options, but also retain the other array that hasn't been changed.
I've tried everything and it doesn't seem like it's working and the update_option('instagram_authenticated_users') doesn't update the values and it retains the same data.
So I want get_option('instagram_authenticated_userss') when called after the update to be the following with the new data (The second index should have been updated):
$authenticated_users = {array} [2]
[0] = {array} [5]
username = "semi_test1"
user_id = {int} 17841449642220098
access_token = "IGQVJWMDJnblBnUGMtMTVFa1NpUGdValNBVUZAyZAWM2OTdSSkRFdmNUbnVOQXJqeFhwbDVmT0c3aXJfamFYdnZANSlpXc3Mwc05PS0tMSzNsbXhES0tkTzNoOEY3RFRIb3dsblBiTXN3"
access_token_expiration = {int} 1651281005
last_updated = {int} 1646181108
[1] = {array} [5]
username = "semi_test2"
user_id = {int} 17841400835712753
access_token = "IGQVJYOEdqQ0hpbmZAHWlFsdDdMNHdUN1hmenhlV2ZAYOTBtMTJiaFhtSjhyUW9DVm9UREtLZAlFQVHhuVE1XUUFBNUF5SHoxdWRJNXd5dUF6ZAkNKeEtNYmVzRzNTWXdGSmhldG9ILTdn" (NEW VALUE)
access_token_expiration = {int} 1651282134 (NEW VALUE)
last_updated = {int} 1646181136 (NEW VALUE)
Can someone spot that I might be doing wrong?
The problem is your foreach is not creating references. You have to explicitly tell it to on which variables.
This solution doesn't try to add in the code you need where you want it to retain both the previous and the current access tokens. But this solution does you show how to change an array "in-place" using foreach, which will correct (or help) in correcting the problem of having the changes stored to the db.
Replace your foreach statement with:
foreach ($authenticated_users as &$user) {
That ampersand on &$user will make the difference: it will create $user by reference. Any changes to it will change $authenticated_users too.
Example:
$a = array("1","apple","3","pear");
foreach ($a as $p) {
if ($p == "apple") $p = "sauce";
}
print_r($a);
/* Outputs:
Array
(
[0] => 1
[1] => apple
[2] => 3
[3] => pear
)
*/
foreach ($a as &$p) {
if ($p == "apple") $p = "sauce";
}
print_r($a);
/* Outputs:
Array
(
[0] => 1
[1] => sauce
[2] => 3
[3] => pear
)
*/
The second foreach changes the source array because of the ampersand sign on $p in the foreach statement.
In this way, the same approach could work for you.
So this is an alternative to using the '&' to pass things by reference, and mutate the original array.
public static function refresh_access_token(string $user_id, string $access_token): bool
{
if (!$authenticated_users = get_option('instagram_authenticated_users')) {
return false;
}
// The code for the cURL request is here (It's not needed for this question).
$array = json_decode($curl_exec);
$newAuthenticatedUsers = [];
foreach ($authenticated_users as $user) {
if ($user['user_id'] === (int) $user_id) {
$user['access_token'] = $array->access_token;
$user['access_token_expiration'] = time() + $array->expires_in;
$user['last_updated'] = (string) time();
}
$newAuthenticatedUser[] = $user;
}
return update_option('instagram_authenticated_users', $newAuthenticatedUser);
}
If you understand what you are doing, and why in this circumstance it works, then great. You also could just as easily use a for loop and update the original array without a foreach at all:
$sizeOf = count($authenticated_users);
for ($i=0; $i < sizeOf; $i++) {
if ($authenticated_users[$i]['user_id'] === (int)$user_id) {
$authenticated_users[$i]['access_token'] = $array->access_token;
$authenticated_users[$i]['access_token_expiration'] = time() + $array->expires_in;
$authenticated_users[$i]['last_updated'] = (string) time();
}
}
return update_option('instagram_authenticated_users', $authenticated_users);
Keep in mind, per my example in the comments, that an array of objects (which is very common when dealing with ORM's and database fetching libraries) is already passed by reference, and you don't want to use a reference in a foreach.
I have this array
$params_array['application_id'] = 'xxxxxxxxx';
$params_array['v'] = 1.20;
$params_array['src'] = 'http://www.google.com/logos/2011/yokoyama11-hp.jpg';
$params_array['functions']['name'] = 'blur';
$params_array['functions']['params']['radius'] = '0.0';
$params_array['functions']['params']['sigma'] = '2.0';
$params_array['functions']['save']['image_identifier'] = 'MY_CLIENT_ID';
I need to transform it into json.
So I am doing this:
$json = json_encode($params_array,JSON_UNESCAPED_SLASHES);
The result is
{"application_id":"xxx","v":1.2,"src":"http://www.google.com/logos/2011/yokoyama11-hp.jpg","functions":{"name":"blur","params":{"radius":"0.0","sigma":"2.0"},"save":{"image_identifier":"MY_CLIENT_ID"}}}
but, the receiver API of that json wants it to be formed slightly different, like this:
{"application_id":"xxx","v":1.2,"src":"http://www.google.com/logos/2011/yokoyama11-hp.jpg","functions":[{"name":"blur","params":{"radius":"0.0","sigma":"2.0"},"save":{"image_identifier":"MY_CLIENT_ID"}}]}
The difference: after "functions": there is this bracket [, and it's closed at the end.
PHP somehow does not create the json with this bracket.
How can I get PHP to create the json with those brackets?
The receiver API is http://www.blitline.com/docs/quickstart
You should prepare your structure this way:
$params_array['application_id'] = 'xxxxxxxxx';
$params_array['v'] = 1.20;
$params_array['src'] = 'http://www.google.com/logos/2011/yokoyama11-hp.jpg';
$params_array['functions'][0]['name'] = 'blur';
$params_array['functions'][0]['params']['radius'] = '0.0';
$params_array['functions'][0]['params']['sigma'] = '2.0';
$params_array['functions'][0]['save']['image_identifier'] = 'MY_CLIENT_ID';
(Making functions to a number indexed array.)
So receiver expects functions to be array objects, but you pass single object instead. Change $params_array['functions']['name'] to $params_array['functions'][$functionIndex]['name']
Try this
$params_array['application_id'] = 'xxxxxxxxx';
$params_array['v'] = 1.20;
$params_array['src'] = 'http://www.google.com/logos/2011/yokoyama11-hp.jpg';
$function_array['name'] = 'blur';
$function_array['params']['radius'] = '0.0';
$function_array['params']['sigma'] = '2.0';
$function_array['save']['image_identifier'] = 'MY_CLIENT_ID';
$params_array['functions'] = array($function_array);
Reason:
JSON_ENCODE will treat an Array as JSON OBJECT if it is like Key=>Value
and it will treat as json array if it is index based like [0] => value
Alright, run this example then you'll know how to achieve it.
$params_array = array();
$params_array['application_id'] = 'xxxxxxxxx';
$params_array['another_array'] = array("A","B","C");
echo json_encode($params_array );
Result: {"application_id":"xxxxxxxxx","another_array":["A","B","C"]}
You can try to use the flag JSON_FORCE_OBJECT if you have PHP 5.4.0 or later :
$json = json_encode($params_array,JSON_UNESCAPED_SLASHES + JSON_FORCE_OBJECT);
so I have an array similar to this
$arr[0]['name'] = 'Name';
$arr[0]['id'] = 2382;
$arr[1]['name'] = 'Name';
$arr[1]['id'] = 2838;
$arr[2]['name'] = 'Name';
$arr[2]['id'] = 2832;
How could I reformat the array replacing the initial index (0, 1, 2) with the id value of the array? Is this possible? The final array would be like this
$arr[1922]['name'] = 'Name';
$arr[2929]['name'] = 'Name';
$arr[3499]['name'] = 'Name';
Thanks
This is fairly straightforward.
It's simply a case of looping over the original array and building the new one as you go along.
Once you've finished you can, if you want, replace the new array with the old one.
foreach ( $arr as $thisArray ) {
$aNewArray[ $thisArray['id']]['name'] = $thisArray['name'];
}
$arr = $aNewArray;
If you have an arbitrary number of elements in the array and you just want to wipe out the ID and keep the rest you can unset the ID as you go along and use the resulting array:
foreach ( $arr as $thisArray ) {
$id = $thisArray['id'];
unset( $thisArray['id'] );
$aNewArray[ $id ] = $thisArray;
}
$arr = $aNewArray;
I have an array called $friend_array. When I print_r($friend_array) it looks like this:
Array ( [0] => 3,2,5 )
I also have a variable called $uid that is being pulled from the url.
On the page I'm testing, $uid has a value of 3 so it is in the array.
However, the following is saying that it isn't there:
if(in_array($uid, $friend_array)){
$is_friend = true;
}else{
$is_friend = false;
This always returns false. I echo the $uid and it is 3. I print the array and 3 is there.
What am I doing wrong? Any help would be greatly appreciated!
Output of
Array ( [0] => 3,2,5 )
... would be produced if the array was created by something like this:
$friend_array = array();
array_push($friend_array, '3,2,5');
print_r($friend_array);
Based on your question, I don't think this is what you meant to do.
If you want to add three values into the first three indexes of the array, do the following:
$friend_array = array();
array_push($friend_array, '3');
array_push($friend_array, '2');
array_push($friend_array, '5');
or, as a shorthand for array_push():
$friend_array = array();
$friend_array[] = '3';
$friend_array[] = '2';
$friend_array[] = '5';
Array ( [0] => 3,2,5 ) means that the array element 0 is a string 3,2,5, so, before you do an is_array check for the $uid so you have to first break that string into an array using , as a separator and then check for$uid:
// $friend_array contains as its first element a string that
// you want to make into the "real" friend array:
$friend_array = explode(',', $friend_array[0]);
if(in_array($uid, $friend_array)){
$is_friend = true;
}else{
$is_friend = false;
}
Working example
Looks like your $friend_array is setup wrong. Each value of 3, 2, and 5 needs its own key in the array for in_array to work.
Example:
$friend_array[] = 3;
$friend_array[] = 2;
$firned_array[] = 5;
Your above if statement will then work correctly.
Suppose you have an associative array
$hash['Fruit'] = 'Apple';
$hash['Name'] = 'Jeff';
$hash['Car'] = 'Ford';
and you cannot change the order in which these variables are created. So Car is always added to the array after Name, etc. What's the prettiest way to add/move Car to the beginning of the associative array instead of the end (default)?
$hash = array('Car' => 'Ford') + $hash;
ksort() ?
But why would you care about the array's internal order?
array_reverse($hash, true);
This is not a very direct solution but one that is:
$value = end($hash);
$hash = array(key($hash) => $value) + $hash;
Another trick is -
$new_items = array('Car' => 'Ford');
$hash = array_merge($new_items, $hash);
You can re arrange the new array keys also. Suppose car first then another field (say Id) then array remain so....
$new_items = array('Car' => 'Ford','Id'=>'New Id');
$hash = array_merge($new_items, $hash);
The array will become like
$hash['Car'] = 'Ford';
$hash['Id'] = 'New Id';
$hash['Fruit'] = 'Apple';
$hash['Name'] = 'Jeff';