0
我正在開發一個應用程序,我將不得不集成GCM功能。 收件人的device_id存儲在MySQL數據庫中,然後通過CURL將其檢索併發送到Google GCM API網址。 問題是,當我這樣做,我收到一條錯誤:將MySQL結果集轉換爲JSON數組以消耗Google GCM API的問題
Recipients_Id field is not a JSON Array.
PHP代碼爲:
//get the recipients gcm_ids
if (isset($_POST["deviceid"]) && isset($_POST["message"]) && isset($_POST["recipient_id"])) {
require_once __DIR__ . '/db_connect.php';
include_once './GCM.php';
$gcm = new GCM();
// connecting to db
$db = new DB_CONNECT();
$device_id=$_POST['deviceid'];
$recipient_id=$_POST['recipient_id'];
$get_details=mysql_query("select id,name from gcm_users where gcm_regid='$device_id' ");
$row_details=mysql_fetch_array($get_details);
$user_name=$row_details["name"];
$user_id=$row_details["id"];
$recipients_gcm_ids=mysql_query("SELECT gcm_regid from gcm_users where id='$recipient_id'");
$rec_gcm1=array();
while($row = mysql_fetch_assoc($recipients_gcm_ids))
{array_push($rec_gcm1,$row);}
$recipients_gcm=array();
$recipients_gcm=json_encode($rec_gcm1);
$message = array("price" => $message1);
$result = $gcm->send_notification($recipients_gcm, $message);
//The class that sends the message to the Google API url
class GCM {
//put your code here
// constructor
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($Recipients_Id, $message) {
// include config
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'Recipients_Id' => $Recipients_Id,
'data' => $message,
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'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);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo "Result Is:".$result;
}
據我所知,這個問題涉及這行代碼:
$result = $gcm->send_notification($recipients_gcm, $message);
但是,我不知道任何方法(但),我會用它來創建一個PHP的JSON數組,除了使用「json_encode」功能。也許是有另一種方式來規避:
"Not a JSON Array" error ?
順便說的print_r($ recipients_gcm)的輸出是:
[{"gcm_regid": "ABCDEFGH12y63i4455u65y4i4p4yu4t3i3zzttyuuiioo"}]