30 Dec 2010

Twilio's PHP library support for JSON

I have been hacking Twilio for some days now and it's been fun.

The Twilio API supports XML and JSON as response formats, XML being the default. Twilio has also been generous to include sample libraries in various languages to play around the API. Thing however is that the PHP library has support for only XML as the response type. Being a fan of JSON (the reduction in data transfer as compared to XML among other things), I added a little hack to the response class in the library.

So here is my new constructor of the TwilioRestResponse class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
// ...
         public function __construct($url, $text, $status) {
             preg_match('/([^?]+)\??(.*)/', $url, $matches);
             $this->Url = $matches[1];
             $this->QueryString = $matches[2];
             $this->ResponseText = $text;
             $this->HttpStatus = $status;
             if($this->HttpStatus != 204) // HTTP 204 => No content
                 $this->ResponseJson = @json_decode($text);
             
             if($this->IsError = ($status >= 400))
                 $this->ErrorMessage =
                     (string) $this->ResponseJson->message;
 
             /*if($this->HttpStatus != 204)
                 $this->ResponseXml = @simplexml_load_string($text);
             
             if($this->IsError = ($status >= 400))
                 $this->ErrorMessage =
                     (string)$this->ResponseXml->RestException->Message;
             //*/
         }

 

Looking for a simple marketing automation tool to automate your customer onboarding, retention and lifecycle emails? Check out Engage and signup for free.

 

My name is Opeyemi Obembe. I build things for web and mobile and write about my experiments. Follow me on Twitter–@kehers.

 

Next post: The cost of free