Since version 3.0, we’ve introduced an updated API for interacting with the Twilio REST API. Gone are the days of manual URL creation and XML parsing.
Before querying the API, you’ll need to create a Services_Twilio instance. The constructor takes your Twilio Account Sid and Auth Token (both available through your Twilio Account Dashboard).
$ACCOUNT_SID = "AC123";
$AUTH_TOKEN = "secret";
$client = new Services_Twilio($ACCOUNT_SID, $AUTH_TOKEN);
You access the Twilio API resources through this $client, specifically the $account attribute, which is an instance of Services_Twilio_Rest_Account. We’ll use the Calls resource as an example.
Iterating over the calls attribute will iterate over all of your call records, handling paging for you. Only use this when you need to get all your records.
The $call object is a Services_Twilio_Rest_Call, which means you can easily access fields through it’s properties. The attribute names are lowercase and use underscores for sepearators. All the available attributes are documented in the Services_Twilio_Rest documentation.
// If you have many calls, this could take a while
foreach($client->account->calls as $call) {
print $call->price . '\n';
print $call->duration . '\n';
}
Many Twilio list resources allow for filtering via getIterator which takes an optional array of filter parameters. These parameters correspond directlty to the listed query string parameters in the REST API documentation.
You can create a filtered iterator like this:
$filteredCalls = $client->account->calls->getIterator(
0, 50, array("Status" => "in-progress"));
foreach($filteredCalls as $call) {
print $call->price . '\n';
print $call->duration . '\n';
}
If you know the unique identifier for a resource, you can get that resource using the get method on the list resource.
$call = $client->account->calls->get("CA123");
get fetches objects lazily, so it will only load a resource when it is needed. This allows you to get nested objects without making multiple HTTP requests.
$participant = $client->account->conferences
->get("CO123")->participants->get("PF123");