Loading JSON web service in to PHP

As I’ve recently had to implement the JSON implementation of the Twitter Search API v1.0 as a hotfix into ThinkTwit, I thought it might be useful to share how I did this…

So if you’re here it’s probably because you need to read JSON in PHP or you have to implement an API, maybe the Twitter API. First of all you need to construct your URL, if you are using the Twitter Search API it may look like this:

// Contstruct a string of usernames to search for
$username_string = str_replace(" ", "+OR+from%3A", $usernames);

// Replace hashes in hashtags with code for URL
$hashtags = str_replace("#", "%23", $hashtags);

// Replace spaces in hashtags with plus signs
$hashtags = str_replace(" ", "+", $hashtags);

// Construct the URL to obtain the Twitter Search JSON feed
$url = "http://search.twitter.com/search.json?q=from%3A" . $username_string . "+" . $hashtags . "&rpp=" . $limit;

where of course $usernames (a list of space separated Twitter usernames), $hashtags (a list of space separated hashtags to filter the search) and $limit (the maximum number of tweets required) are already defined.

Line 1 formats the usernames so that it works within the search, lines 4 and 7 do the same for hashtags and line 10 adds both to a URL. Once called, this URL will return a JSON feed containing the tweets matching your search requirements.

To make the call there are a number of ways. Within ThinkTwit I have implemented two options which the administrator can choose from as not all web servers are the same and some will only support one method:

// If user wishes to use CURL
if ($use_curl) {
	// Initiate a CURL object
	$ch = curl_init();

	// Set the URL
	curl_setopt($ch, CURLOPT_URL, $url);

	// Set to return a string
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

	// Set the timeout
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

	// Execute the API call
	$feed = curl_exec($ch);

	// Close the CURL object
	curl_close($ch);
} else {
	// Execute the API call
	$feed = @file_get_contents($url);
}

Here the first part of the if-statement (lines 2-19) sets the conditions for using CURL and then makes the call and the else-statement (lines 20-23) simply make the call using a standard PHP function. The if-statement itself is simply checking a boolean that indicates which method should be used – as standard I would recommend not using CURL unless you are having issues as it needs to be installed separately in to the web server.

$feed will now contain your JSON, which is probably the bit you are really looking for. I’m afraid to say, this is also the shortest part of this article as it’s actually very easy!

// Decode the JSON feed
$json = json_decode($feed, true);

// Get the tweets from the JSON feed
$json_tweets = $json["results"];
			
// Check that values were returned
if (is_array($json_tweets)) {
	// Loop through the tweets
	foreach($json_tweets as $tweet) {
		// Get the content of the tweet
		echo "Tweet: " . $tweet["text"];
	}
}

Line 2 will decode your returned $feed into an Array which you are free to process as you wish. If you are following the Twitter Search API example then you’ll also want to know that line 5 accesses the tweets themselves; line 8 checks that the Array has been properly constructed; line 10 iterates through each tweet and line 12 simply outputs the content of the tweet.

Here’s an example of what is actually returned; it should quite simple to work out how to access different parts of data that is returned as they are all different parts of the array and occasionally an embedded array.

{
  completed_in: 0.016,
  max_id: 252331110321770500,
  max_id_str: "252331110321770496",
  next_page: "?page=2&max_id=252331110321770496&q=from%3Astephenpickett&rpp=2",
  page: 1,
  query: "from%3Astephenpickett",
  refresh_url: "?since_id=252331110321770496&q=from%3Astephenpickett",
  results: [
    {
      created_at: "Sun, 30 Sep 2012 08:56:39 +0000",
      from_user: "stephenpickett",
      from_user_id: 27642700,
      from_user_id_str: "27642700",
      from_user_name: "Stephen Pickett",
      geo: null,
      id: 252331110321770500,
      id_str: "252331110321770496",
      iso_language_code: "en",
      metadata: {
        result_type: "recent"
      },
      profile_image_url: "http://a0.twimg.com/profile_images/1440714767/web_normal.png",
      profile_image_url_https: "https://si0.twimg.com/profile_images/1440714767/web_normal.png",
      source: "<a href="http://twitter.com/tweetbutton">Tweet Button</a>",
      text: "An excellent example of data misinterpretation - BBC News - North Sea cod: Is it true there are only 100 left? http://t.co/0i9KIHM7",
      to_user: null,
      to_user_id: 0,
      to_user_id_str: "0",
      to_user_name: null
    },
    {
      created_at: "Sat, 29 Sep 2012 12:11:33 +0000",
      from_user: "stephenpickett",
      from_user_id: 27642700,
      from_user_id_str: "27642700",
      from_user_name: "Stephen Pickett",
      geo: null,
      id: 252017772719140860,
      id_str: "252017772719140864",
      iso_language_code: "en",
      metadata: {
        result_type: "recent"
      },
      profile_image_url: "http://a0.twimg.com/profile_images/1440714767/web_normal.png",
      profile_image_url_https: "https://si0.twimg.com/profile_images/1440714767/web_normal.png",
      source: "<a href="http://twitter.com/tweetbutton">Tweet Button</a>",
      text: "Consumers failing to protect prized gadgets - http://t.co/6mMS6g2X",
      to_user: null,
      to_user_id: 0,
      to_user_id_str: "0",
      to_user_name: null
    }
  ],
  results_per_page: 2,
  since_id: 0,
  since_id_str: "0"
}

About Stephen Pickett


Stephen Pickett is a programmer, IT strategist, project manager, RightNow and telephony expert, information security specialist, all-round geek. He is currently Professional Services Director at Connect Assist, a social business that helps charities and public services improve quality, efficiency and customer engagement through the provision of helpline services and CRM systems.


Stephen is based in south Wales and attended Cardiff University to study Computer Science, in which he achieved a 2:1 grading. He has previously worked for Think Consulting Solutions, the leading voice on not-for-profit fundraising, Fujitsu Services and Sony Manufacturing UK as a software developer.


Stephen is the developer of ThinkTwit, a WordPress plugin that allows you to display multiple Twitter feeds within a blog.


3 thoughts on “Loading JSON web service in to PHP

  1. This blog has great essence of technical knowledge. This is awesome. Thanx for penning down your experience. Thanx once again. I’ve been reading many web hosting blogs, web development blogs, but I believe this one stands tall.

  2. Hi Shashank,

    No problem, and thanks very much for your kind comments. I’m glad it has come in handy for you and others, I initially started the blog to remember things for myself but also to share my solutions so that other people wouldn’t have to repeat my troubles so I’m really happy that people are finding it helpful 🙂

Leave a Reply