1

我对 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;
}

4

2 回答 2

1

JSON中的简单解码响应

$data = json_decode($response);

这个 if 的输出

 
{
    “multicast_id”:5020929399500020011,
    “成功”:0,
    “失败”:1,
    “canonical_ids”:0,
    “结果”: [{
        “错误”:“未注册”
    }]
}

现在您可以轻松解析错误并生成 json。

希望这对你们有帮助。

于 2014-07-07T04:33:37.680 回答
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' );
于 2012-11-13T01:40:16.783 回答