2017-08-07 172 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,请查看我编辑的答案。 –