This question already has an answer here:
i am new to php. i am implementing Firebase push notification service in PHP .
The required json object is like
{ "data": {
"score": "5x1",
"time": "15:10"
},
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}
Now in firebase i have to send my data in this format but i am not sure how to make JSON object of this data and use this object in firebase .
And if I want to use Array of IDs then how this will work?
As per official firebase documentation they didn't define method to use array of ID's.
https://firebase.google.com/docs/cloud-messaging/downstream
</div>
Create an array in a same format that you want to sent to Firebase like bellow
$arr = ['data'=> [
'score'=> "5x1",
'time'=> "15:10"
],
"to" => "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
];
and then use the php function json_encode(var); and it will return you the json object.
json_encode($arr)
and if i want to use Array of id then how this will work. I am not sure about this.
If you are trying to send a POST with PHP you could use cURL:
<?php
$firebase_url = 'https://fcm.googleapis.com/fcm/send';
$message = [
"data" => [
"score" => "5x1",
"time" => "15:10"
],
"to": "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
];
$json_message = json_encode($message);
//open connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $firebase_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_message);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($json_message)
]);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
//execute post
$result = curl_exec($ch);
print $result;
I will recommend using Guzzle which is a third party library and cleaner and more usable/understandable. To install it:
php composer.phar require guzzlehttp/guzzle
And some examples here: http://docs.guzzlephp.org/en/latest/