Back to Blog

Output clean JSON data from Twitter API v1.1 using PHP

Sun, 01 Sep 2013, by Syrsly

I was making a mobile app with Tersus (WYSIWYG RAD) as a school project, and I noticed Twitter no longer has an open XML feed. I looked around and most of the Twitter apps I saw were outdated or simply used the Twitter widget (JS only). For that reason, I took a few hours out of my day to develop a workflow for interacting with Twitter in PHP using the TwitterOAuth library, which is a very nice object-oriented abstraction layer for the generic OAuth library (included with previously mentioned library).

Now, I must say that retrieving and displaying the data from my user timeline was a lot more of a hassle than I thought it would be.
Here is the basic code I used to get a working JSON output from a PHP script:

$tdata = $connection->get("statuses/user_timeline"); $count = count($tdata); //counting the number of status $content = array(); for($i=0;$icreated_at = $tdata[$i]->created_at; $contentTemp->text = $tdata[$i]->text; $content[] = $contentTemp; } print json_encode($content);

Let us recap what this does real quick.

First, it calls the get() method from the connection object, which is simply an instance of the TwitterOAuth class. Then, it stores a count of how many status posts are retrieved. Then, it creates a new array that will act as the container for the data we want to keep. The rest is a simple for loop for storing the data we want to keep from each status post.

As you may be able to observe on your own, I left out the bit about authentication. That part was a little confusing but not too much so. It basically requires you to fill in four pass codes which are generated by the Twitter app admin page. Fortunately, all you have to do is sign into your account and create an app profile. Yes, you need an app profile just to retrieve your user timeline. It is very silly, I know.
I still have not figured out how to get the data to display in Tersus, which infuriates me, because this task should be a simple two-step process of retrieving and displaying data. It requires a lot more work than that for some reason. If any of you knows how to get a Twitter feed working in Tersus, let me know and please, send me your project file. Otherwise, wish me luck.

Update, August 2024: The above code is no longer functional. This blog post is left here for historical reasons. Twitter's API is very different and way more locked down these days. I'm not going to pay for their API access to create something new for it.