Where in my application will I be using TwiML?
In our Twilio account, we can buy phone numbers which are attached to to a particular URL. Twilio will make a GET
or POST
request to that URL, in order to fetch TwiML when there's an inbound call or message. The TwiML we return tells Twilio what to do in response to the call or Short Message Service (SMS).
When something happens with our phone number—namely an inbound call or incoming SMS—Twilio sends us a webhook that tells us about what's going on and allows us to direct what happens.
We'll also use TwiML when we place outbound calls using Twilio's REST API. To make a call, we have to specify the URL for a piece of TwiML that will handle that call. Once the dialed party picks up, Twilio will go through that markup, perhaps playing a message or recording its input. As part of its webhooks, Twilio provides information such as the number called and the phone number of the caller in the headers. This means you can customize what you ask Twilio to do based on a variety of different data points related to the call.
For instance, by constructing the right TwiML, you can ask Twilio's text-to-speech engine to read some text, play an MP3, dial a call, and many other things.
You can serve up your TwiML from whichever framework, language, and web server you're using. In my examples, I'll use PHP, but it's equally possible to work in the same way in Ruby (on Rails) or any other language.
PHP makes building powerful and dynamic TwiML very simple, as we can easily change the outputted XML using familiar control structures, such as if
and else
, which are embedded right on our page.
If you're using a PHP framework, such as Laravel or Cake, or a similar one in other languages, such as Ruby's Ruby on Rails, you'll be able to build XML templates using your usual templating library just as you would for HTML pages.