2017-08-07 142 views
1

所以我使用Twilio API發送短信。
保持Twilio失敗後發送短信?

我從我的數據庫中獲取usr名稱和nr,我把它放在一個PHP數組中。
然後我發短信與foreach循環:

foreach ($usrs as $number => $name) { 

    $sms = $client->account->messages->create($number, 
     array(
      'from' => "xxxxxxxxxxxx", 
      'body' => "Hi $name. $text" 
     ) 
    ); 

    // Display a confirmation message on the screen 
    echo "Sent message to $name <br>"; 
} 

此代碼是什麼是定製的。
它迴應成功。

但如果isn't有效一些,該過程將像一個錯誤信息停止:

Sent message to David 
Sent message to Elsa 
Sent message to Adam 
Failure notice: the number is not a valid phone number... 

,這裏的循環中斷..

什麼我倒是喜歡的是環打印出失敗消息,但仍然發送失敗後出現的數組中的一個。而不會打破循環。

錯誤消息必須來自API dist文件?
因爲我無法瑟任何錯誤在我定製的PHP文件處理..

+2

它是一個例外呢?在這種情況下,圍繞SMS創建呼叫使用try catch並相應處理。 –

+0

@JonStirling,打我吧。 –

回答

1

正如評論所說,你需要使用try{}catch{}

下面是一個例子:

// Step 1: set our AccountSid and AuthToken from https://twilio.com/console 
    $AccountSid = "XXX"; 
    $AuthToken = "XXX"; 

    $client = new Client($AccountSid, $AuthToken);   

foreach ($usrs as $number => $name) { 
    try { 
     $sms = $client->account->messages->create(

      // the number we are sending to - Any phone number 
      $number, 

      array(
       // Step 2: Change the 'From' number below to be a valid Twilio number 
       // that you've purchased 
       'from' => "+XXXXXXXXXXX", 

       // the sms body 
       'body' => $sms 
      ) 
     ); 

     // Display a confirmation message on the screen 
     echo "Sent message to $name"; 

    } catch (TwilioException $e) { 
     die($e->getCode() . ' : ' . $e->getMessage()); 
    } 

} 
+0

謝謝。我會試試這個!請注意,您錯過了您的answear的foreach循環; D –

+0

@BjörnC,請查看我編輯的答案。 –