Android中的错误:使用PHP的GCM
我在PHP中使用以下代码向Android发送GCM消息:Android中的错误:使用PHP的GCM,php,android,google-cloud-messaging,Php,Android,Google Cloud Messaging,我在PHP中使用以下代码向Android发送GCM消息: <?php $apiKey = "xxxxx"; //my api key $registrationIDs = array("APA91bGGN7o7AwVNnv35lwP5Jw8OTJQL331XcxPfEIu4xt-ZKLe6R0aSSbAve99uKSDXhzE9L2PVLihpqFt0DEawhymUs9h5ICbTMweMAEJypg6ZLFqmf6SOGlyULQzudw9MM1DjbPaaKbo--wxWoHGk
<?php
$apiKey = "xxxxx"; //my api key
$registrationIDs = array("APA91bGGN7o7AwVNnv35lwP5Jw8OTJQL331XcxPfEIu4xt-ZKLe6R0aSSbAve99uKSDXhzE9L2PVLihpqFt0DEawhymUs9h5ICbTMweMAEJypg6ZLFqmf6SOGlyULQzudw9MM1DjbPaaKbo--wxWoHGkjyec2H_63e7mesYjaRf4_rgxBe655M0");
// Message to be sent
$message = "Message Text";
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $message ),
);
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
echo $result;
我终于找到了解决办法。我使用for循环将所有结果放入一个数组,并使用
JSON_encode()将数组转换为JSON数组代码>由于数组索引没有正确排序,我得到了相同的错误。我使用PHP的sort()函数修复了这个错误
排序前的
$registration_ids = Array
(
[1] => "xxx"
[6] => "xxx"
[8] => "xxx"
)
sort($registration_ids);
$registration_ids = Array
(
[0] => "xxx"
[1] => "xxx"
[2] => "xxx"
)
排序
$registration_ids = Array
(
[1] => "xxx"
[6] => "xxx"
[8] => "xxx"
)
sort($registration_ids);
$registration_ids = Array
(
[0] => "xxx"
[1] => "xxx"
[2] => "xxx"
)
排序后
$registration_ids = Array
(
[1] => "xxx"
[6] => "xxx"
[8] => "xxx"
)
sort($registration_ids);
$registration_ids = Array
(
[0] => "xxx"
[1] => "xxx"
[2] => "xxx"
)
传递到PHP的cURL
$fields = array(
'registration_ids' => $ids,
'data' => array('message' => $data)
);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));