2015-04-23 75 views
5

当我使用GCM时,出现如下错误:字段“数据”必须是JSON数组。任何人都有如何解决它的想法?谢谢。 有我的代码第一部分,省略部分代码:GCM返回错误:字段数据必须是json数组

<?php 

$gcm_regid = array(); 
$gcm_data = array(); 
while ($row = mysql_fetch_array($result)) { 
array_push($gcm_regid, $single_gcm_regid); 
array_push($gcm_data , $notificationMessage); 
} 

?> 

这里是第二部分:

<?php 

$url = 'https://android.googleapis.com/gcm/send'; 

$apiKey = '******************************'; 
$registrationIDs = $gcm_regid; 

$data = $gcm_data; 

$fields = array('registration_ids' => $registrationIDs, 
      'data' => $data); 

//http header 
$headers = array('Authorization: key=' . $apiKey, 
      'Content-Type: application/json'); 

//curl connection 
$ch = curl_init(); 

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_SSL_VERIFYPEER, false); 
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); 

$result = curl_exec($ch); 

curl_close($ch); 

echo $result; 
?> 

回答

0

使用json_encode$fields对象返回JSON表示的。

看看接受的答案here,看看它是如何使用的。

4

从代码中的第5行更改

$message = $gcm_data; 

$fields = array(
    'registration_ids' => $registrationIDs, 
    'data' => array("message" =>$message) 
); 
相关问题