How to grab this nested string in JSON with PHP? - php

I am looping through email bodies that are nothing but JSON output. I am trying to grab a single string emailAddress, but I am unsure of the syntax. I am able to get to the Message portion of the JSON, but anything else I try to access, I end up getting Illegal string offset.
So, if my JSON is:
[Type] => Notification
[MessageId] => gibberishhere
[TopicArn] => arn:aws:somethingsomethingsomething
[Message] => {
"notificationType":"Bounce",
"bounce":{
"feedbackId":"blahblahblahblahblah",
"bounceType":"Permanent",
"bounceSubType":"General",
"bouncedRecipients":[{
"emailAddress":"bounce#simulator.amazonses.com",
"action":"failed",
"status":"5.1.1",
"diagnosticCode":"smtp; 550 5.1.1 user unknown"}],
"timestamp":"2020-11-02T16:37:13.000Z",
"remoteMtaIp":"ip.address.here",
"reportingMTA":"dsn; somethingsomething"},
"mail":{
"timestamp":"2020-11-02T16:37:13.029Z",
"source":"test#emailaddress.com",
"sourceArn":"arn:somethingsomethingdotcom",
"sourceIp":"ip.address.here",
"sendingAccountId":"somethingsomething",
"messageId":"numbersnumbersnumbers1234567890",
"destination":["bounce#simulator.amazonses.com"]
}
}
[Timestamp] => 2020-11-02T16:37:13.677Z
[SignatureVersion] => 1
[Signature] => blahblahblah
[SigningCertURL] => blahblahblah
[UnsubscribeURL] => blahblahblah
And I have this to decode it:
$message = json_decode($message, true);
echo $message['Message'];
I get this output:
{
"notificationType":"Bounce",
"bounce":{
"feedbackId":"blahblahblahblahblah",
"bounceType":"Permanent",
"bounceSubType":"General",
"bouncedRecipients":[{
"emailAddress":"bounce#simulator.amazonses.com", <---- I NEED THIS FIELD
"action":"failed",
"status":"5.1.1",
"diagnosticCode":"smtp; 550 5.1.1 user unknown"}],
"timestamp":"2020-11-02T16:37:13.000Z",
"remoteMtaIp":"ip.address.here",
"reportingMTA":"dsn; e226-55.smtp-out.us-east-2.amazonses.com"},
"mail":{
"timestamp":"2020-11-02T16:37:13.029Z",
"source":"test#emailaddress.com",
"sourceArn":"arn:somethingsomethingdotcom",
"sourceIp":"ip.address.here",
"sendingAccountId":"somethingsomething",
"messageId":"numbersnumbers1234567890",
"destination":["bounce#simulator.amazonses.com"]
}
}
All I need is the emailAddress field. How far in do I need to go to grab it? I've tried
$message['Message']['bounce'], $message['Message']['emailAddress'], and several others, but they all return Illegal string offset.

Working with an associative array is relatively easy, so as suggested in the comment:
$arr = json_decode($message['Message'], true);
Now all you need to do is reference the correct element, follow the path:
echo $arr['bounce']['bouncedRecipients'][0]['emailAddress'];
Which gives:
bounce#simulator.amazonses.com
EDIT: How to reference element emailAddress - explain the [0] index
To get a good view of the array structure of $arr, you can use:
echo '<pre>';
print_r($arr);
echo '</pre>';
Which outputs:
Array
(
[notificationType] => Bounce
[bounce] => Array
(
[feedbackId] => blahblahblahblahblah
[bounceType] => Permanent
[bounceSubType] => General
[bouncedRecipients] => Array
(
[0] => Array
(
[emailAddress] => bounce#simulator.amazonses.com
[action] => failed
[status] => 5.1.1
[diagnosticCode] => smtp; 550 5.1.1 user unknown
)
)
[timestamp] => 2020-11-02T16:37:13.000Z
[remoteMtaIp] => ip.address.here
[reportingMTA] => dsn; e226-55.smtp-out.us-east-2.amazonses.com
)
[mail] => Array
(
[timestamp] => 2020-11-02T16:37:13.029Z
[source] => test#emailaddress.com
[sourceArn] => arn:somethingsomethingdotcom
[sourceIp] => ip.address.here
[sendingAccountId] => somethingsomething
[messageId] => numbersnumbers1234567890
[destination] => Array
(
[0] => bounce#simulator.amazonses.com
)
)
)
Now all you need to do is follow the 'path' to the element you'd like to reference. I.e. for emailAddress let's take the reverse 'route':
emailAddress lives in an array with key [0] (there you have it, key [0])
key [0] lives in an array with key [bouncedRecipients]
key [bouncedRecipients] lives in an array with key [bounce]
key [bounce] lives in the root of array $arr.
So there you have it, the path to your element:
['bounce']['bouncedRecipients'][0]['emailAddress']

Related

PHP array (yaml) - add or remove sections of config file

I have some software that uses a yaml config file and I want to dynamically add a list of registered users to the config file when they join and remove them when their accounts are deleted.
The config file is as follows:
targets:
users:
- name: AlFredo01
uid: a1fa36h2a5hbd6535c919402ba8cc837bd75abfae
userinfo:
- email: Alfredo01#gmail.com
- gender: male
- country: it
- name: AlFredo02
uid: jmed8d83m4mtjf7f7f8j299d8210sla9010labvab10
userinfo:
- email: Alfredo02#gmail.com
- gender: male
- country: gb
I effectively would like to be able to add in new names and remove by name or UID using a PHP script on register/archive.
All the info needed would be available on registration. On deleting, their UID/Name is stored in the DB exactly how it will be added to the config file.
Can this be achieved, please?
I've never used yaml files before. I've found php-yaml and I can parse the data in to an array and print or dump it.
<?
$parsed = yaml_parse_file('config2.yml');
var_dump($parsed);
?>
The above does dump the data as you would expect. Like below
Array
(
[targets] =>
[users] => Array
(
[0] => Array
(
[name] => AlFredo01
[uid] => a1fa36h2a5hbd6535c919402ba8cc837bd75abfae
[userinfo] => Array
(
[0] => Array
(
[email] => Alfredo01#gmail.com
)
[1] => Array
(
[gender] => male
)
[2] => Array
(
[country] => it
)
)
)
[1] => Array
(
[name] => AlFredo02
[uid] => jmed8d83m4mtjf7f7f8j299d8210sla9010labvab10
[userinfo] => Array
(
[0] => Array
(
[email] => Alfredo02#gmail.com
)
[1] => Array
(
[gender] => male
)
[2] => Array
(
[country] => gb
)
)
)
)
)
I'd like to be able to effectively remove a full block based on UID.
So if I wanted to remove Alfredo02, I'd remove this section
[1] => Array
(
[name] => AlFredo02
[uid] => jmed8d83m4mtjf7f7f8j299d8210sla9010labvab10
[userinfo] => Array
(
[0] => Array
(
[email] => Alfredo02#gmail.com
)
[1] => Array
(
[gender] => male
)
[2] => Array
(
[country] => gb
)
)
)
)
Based on UID: jmed8d83m4mtjf7f7f8j299d8210sla9010labvab10
Additionally, I'd like to be able to add a full section in for a new user.
I've tried basic lines to get things like the array ID to start with but keep getting nothing returned.
$search = array_search('jmed8d83m4mtjf7f7f8j299d8210sla9010labvab10', array_column($parsed, 'uid'));
Could anyone please help me with a method of removing and adding data? Once I can generate a new "output" with data added or removed, I can write that back to the config.yml file.
Through investigation and determination I have figured out a way which allows you to remove from the array and write back to the yml file with the removed block/user.
$search = print_r(array_search('jmed8d83m4mtjf7f7f8j299d8210sla9010labvab10', array_column($parsed[users], 'uid', true)));
unset($parsed[users][$search]);
echo '<pre>' , print_r($parsed) , '</pre>';
yaml_emit_file("config2.yml",$parsed);
This effectively allows you to search for your uid inside of users and then print the result on the page using echo, but you can remove this.
Then writing the whole output back to the yml file using yaml_emit_file.
The next stage will be working out how to add a new user in to the array and write that back where necessary.
I'll update when I get to that point for the benefit of others.

PHP read first item in object array

I have my code in PHP which is returning this Array of data:
GoCardlessPro\Core\ListResponse Object
(
[records] => Array
(
[0] => GoCardlessPro\Resources\Mandate Object
(
[model_name:protected] => Mandate
[created_at:protected] => 2017-04-01T16:49:09.642Z
[id:protected] => ID001
[links:protected] => stdClass Object
(
[customer_bank_account] => CB001
[creditor] => CR001
[customer] => CU001
)
[metadata:protected] => stdClass Object
(
)
[next_possible_charge_date:protected] => 2017-04-06
[payments_require_approval:protected] =>
[reference:protected] => RE001
[scheme:protected] => bacs
[status:protected] => active
[data:GoCardlessPro\Resources\BaseResource:private] => stdClass Object
(
[id] => 123
[created_at] => 2017-04-01T16:49:09.642Z
[reference] => RE001
[status] => active
[scheme] => bacs
[next_possible_charge_date] => 2017-04-06
[payments_require_approval] =>
[metadata] => stdClass Object
(
)
[links] => stdClass Object
(
[customer_bank_account] => 001
[creditor] => CR001
[customer] => CU001
)
)
[api_response] =>
)
)
)
I want to be able to read the ID of the first item in therecords array.
This data is contained inside a variable called $GC_Mandate;
I have tried these:
echo $GC_Mandate->records->{0}->id;
echo $GC_Mandate->records->0->id;
echo $GC_Mandate->records->[0]->id;
$GC_Mandate = $GC_Mandate->records;
echo $GC_Mandate->{0}->id;
But none will return the data
To get the first record, the syntax you need is $GC_Mandate->records[ 0 ].
However, that object is a GoCardlessPro\Resources\Mandate object and its member id is protected1, so we'd need to know the interface of GoCardlessPro\Resources\Mandate (its public methods1), to know if we can somehow retrieve the value of id.
My guess would be getId(), so the full syntax would become
$GC_Mandate->records[ 0 ]->getId()
But, that's just a guess. You'd have to look into the documentation/class definition of GoCardlessPro\Resources\Mandate, to be sure if you can retrieve id.
Turns out (provided I'm linking to the correct github repository) you can do:
$GC_Mandate->records[ 0 ]->id
since GoCardlessPro\Resources\Mandate extends GoCardlessPro\Resources\BaseResource, which exposes the protected members through GoCardlessPro\Resources\BaseResource::__get()2.
1. visibility in PHP
2. magic methods in PHP
I can't comment so I guess I'll have to post.
You should try to print_r($GC_Mandate); and see what it gives out and then go from there.
Try $GC_Mandate->records[0]->__get('id')
it will return all data ..for perticulat data put this in foreach loop
print_r($GC_Mandate['records']);

How can I access ID array of its value

I am analyzing someone's else code where I found during debugging the type and values of a class variable during run time:
echo print_r($this->_out);
Array
(
[id] => -1
[fieldErrors] => Array
(
)
[error] =>
[data] => Array
(
)
[row] => Array
(
[DT_RowId] => row_177
[id] => 177
[last_name] => sdfdsf
[first_name] => dsf
[homeaddr] => sdfdsfsdfdsfdsfdsfdsf
[email] => s#jj.com
[officeaddr] => wwwwwwwwwwwwwwwwwwwwwwww
[mobile] => 11111111
[age] => 11
[chargeamt] => 11
[start_date] => 11/11/2011
)
)
1{"row":{"DT_RowId":"row_177","id":"177","last_name":"sdfdsf","first_name":"dsf","homeaddr":"sdfdsfsdfdsfdsfdsfdsf","email":"s#jj.com","officeaddr":"wwwwwwwwwwwwwwwwwwwwwwww","mobile":"11111111","age":"11","chargeamt":"11","start_date":"11\/11\/2011"}}
I am a newbie in PHP and would like to know how I can access [id] => 177 value i.e. value 177.
I tried out many ways
$this->_out['row']['id'][0]
It gave me below result:
1{"row":{"DT_RowId":"row_177","id":"177","last_name":"sssss","first_name":"ss","homeaddr":"sssssssssssssssssssss","email":"ss#ww.com","officeaddr":"sssssssssssssssssssssssssssss","mobile":"11111111","age":"11","chargeamt":"11","start_date":"01\/01\/2001"}}
while
I tried out many ways
$this->_out['row']['id']
It gave me below result:
177{"row":{"DT_RowId":"row_177","id":"177","last_name":"sssss","first_name":"ss","homeaddr":"sssssssssssssssssssss","email":"ss#ww.com","officeaddr":"sssssssssssssssssssssssssssss","mobile":"11111111","age":"11","chargeamt":"11","start_date":"01\/01\/2001"}}
and others but its just not giving me the expected.
How can I access the value as desired?
You are doing it right. $this->_out['row']['id'] will return desired result (check why you get also JSON string that is not part of print_t($this->_out).
This will return result 177:
$this->_out['row']['id'];
And since in PHP you can access string characters as array, this will returns first character in string (that is 1):
$this->_out['row']['id'][0];
And this will throw error as there is no such index (string length is 3, so last index is 2):
$this->_out['row']['id'][5];
The print_r result is an array with more arrays on it. So first of all you must find the index of the main array which index represents the sub-array with the value you are looking for. And then you must use this index to access the sub array values.

PHP Array is filled with data, but can't return values

I have an array $presettings
print_r($presettings); outputs:
Array (
[0] => stdClass Object (
[uuid] => xxx-1ef8-aac6-xxx-xxx
[name] => etime
[owner] => eder112T Resident
[online] => 1
[channel] => 63b525ae-xxx-3555-1c74-xxx
[owner_uuid] => a371751c-eb77-xxx-899c-xxx
[simname] => Plainfield
[slurl] => xxx://xxx/xx/xx/243/24/xx/?title=xx
[design] => 2
[msg_oftheday] => two
[machine_name] => one
[autopay] =>
[autolog_leave] =>
[autolog_offline] =>
[allow_activation] =>
)
)
and now i want to get a special key:
echo "test output : "$presettings['machine_name']." testend";
outputs "" (nothing).
my method look like this
function preloadSettingsFromMYSQL($ownername,$prim_uuid)
{
$result = $this->instance->get_rows("SELECT * FROM etime_rims where owner='".$ownername."' AND uuid='".$prim_uuid."'");
return $result;
}
$result is an object array, also tried it with $presettings->machine_name, did not work too.
where is the error?
thank you.
If you look closely in the print_r result, you can see that there is a 0 there, meaning that those values aren't directly in $presettings, but actually in the first element of $presettings.
Just try:
$presettings[0]->machine_name
You object is multi dimensional so just add a level
$presettings[0]->machine_name;
As side note you have an object here and not array do don't try to access alues with scopes.
In your array, you have stdClass Object at index 0. You're looking to access the object's variables, which is a slightly different syntax than arrays:
echo $presettings[0]->machine_name;

PHP: How to extract a property from this array

I have an array of values returned from Facebook - let's call it $array.
If I do print_r($array) - it looks like this:
Array
(
[code] => 200
[headers] => Array
(
[0] => Array
(
[name] => Some value
[value] => *
)
[1] => Array
(
[name] => Some value
[value] => Some value
)
[2] => Array
(
[name] => Some value
[value] => Some value
)
)
[body] => {"about":"Some more values.","can_post":true}
)
I need to extract the body part from this array.
I cannot refer to it by it's position, I'm looking for something like $array->body and receive the {....} string.
$array->body would work if the variable $array was an object
For arrays, just use:
$body = $array['body'];
(see: http://be2.php.net/manual/en/language.types.array.php)
If you want to access to your array via -> just do 1 more step:
$array = (object) $array;
And now, you can access to your body via:
$array->body;
Else without this step there is just one way:
$array['body'];
If you are more interested about converting arrays into objects, you can visit this question: How to convert an array to object in PHP?
Access array elements by using their name.
$array['body'];

Categories