如何从GCM json解码响应中提取错误消息

时间:2012-11-13 01:29:30

标签: php

我对PHP很新,而且我已经陷入了这个大时代。

我正在尝试在此实例中提取错误消息“ InvalidRegistration ”,该消息似乎位于数组中的数组中,然后在我的PHP服务器中对其进行过滤和处理。

请注意,对于多个regId的多播消息,错误数组的深度可能大于1。

非常感谢任何帮助,谢谢!


转储GCM服务器响应:

object(stdClass)#3(5){[“multicast_id”] => int(6225919148914620552)[“success”] => int(0)[“failure”] => int(1)[“canonical_ids”] => int(0)[“results”] => array(1){[0] => object(stdClass)#4(1){[“error”] => string(19)“ InvalidRegistration ”}}}

发送消息代码:

    $dbf = new push_db_functions();  

    // a row id which contains an intentionally bad regId
    // to trigger the error from 'test' mySql database
    $id = '19'; 

    $result = $dbf->sendMessage($id);

    // dump GCM server response  
    $obj2 = json_decode($result);  
    var_dump($obj2);

   // TODO: (Question Subject)
   // how to extract and test for if('failure' == 1) { ...?
   // and then how to extract 'error' message so I can act upon it appropriately?

发送邮件帮助程序代码:

public function sendMessage($id) {
    $sqlquery = "SELECT regid FROM test WHERE Id = '$id'";
    $results = mysql_query($sqlquery);
    $processed = mysql_fetch_row($results);
    $url = 'https://android.googleapis.com/gcm/send';
    $apiKey = "my api key";
    $message = "Hello World";
    $fields = array('registration_ids' => $processed, '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
    $response = curl_exec($ch); 
    curl_close($ch);
    return $response;
}

2 个答案:

答案 0 :(得分:1)

JSON中的简单解码响应

 $data = json_decode($response); 

此输出

 
{
    "multicast_id": 5020929399500020011,
    "success": 0,
    "failure": 1,
    "canonical_ids": 0,
    "results": [{
        "error": "NotRegistered"
    }]
}

现在你可以轻松地解析错误并导致json。

希望这会帮助你们。

答案 1 :(得分:0)

要获取给定的错误代码,您应该可以使用

$obj2->results[0]->error;

但如果你想灵活地做,你可能希望做更多的事情......

$errors = array();

if( !empty($obj2->results) ) {
    foreach( $obj2->results as $result ) {
        $error = $result->error;
        // Do whatever you want with the error here. 
        // In this instance, I'm just putting it into a fancy array
        $errors[] = $error;
    }
}

// $errors = array( [0] => 'InvalidRegistration' );