~ overflow ~

Tag: json

Custom twitter data fetching in php with cache

by z3n on May.28, 2010, under Coding, Tips & Hints

Problem:

I had to fit the twitter posts (“tweets”) on a site using a special layout, without all the regular twitter crapola

Solution:

There’s this old script that return contents as json, although i could simply add it to the javascript, it would slow down the site, everytime a new page was loaded user would need to fetch tweets all over again, so i did a little php function to fetch it cache and add to the output:

function _ld_twitter($profile=_twitter_profile,$tweets=_twitter_tweets) { // v1.0
	// check cache
	$hash=md5(md5($profile).md5($tweets));
	if (_twitter_cache && file_exists(_twitter_cache_path.$hash.".idx") && file_exists(_twitter_cache_path.$hash) && _fs(_twitter_cache_path.$hash.".idx") > getmicrotime())
		return _fs(_twitter_cache_path.$hash);

	// build
	$x=file_get_contents("http://twitter.com/statuses/user_timeline/".$profile.".json?callback=x&count=".$tweets);
	if ($x != "") {
		$x=json_decode(substr($x,2,-2));
		$b=_fs(templates."twitter".file_ext);$r="";$i=count($x)-1;
		foreach ($x as $k => $v)
			$r.=str_replace(array(
				"##WHO##","##IMG##",
				"##WHEN##","##MSG##",
				"##DELAY##","##LAST##"
				),array(
					$v->user->screen_name,$v->user->profile_image_url,
					date(_dt2,strtotime($v->created_at)),not_utf8($v->text),
					duration(getmicrotime()-strtotime($v->created_at),1,0),$k == $i ? " id='last'" : ""
			),$b);
		// do cache
		if (_twitter_cache) {
			_fw(_twitter_cache_path.$hash.".idx",(_twitter_cache_life*60) + getmicrotime(),"w");
			_fw(_twitter_cache_path.$hash,$r,"w");
		}
		// return
		return $r;
	} else {
		return false;
	}
}

// defines -- yes not formatted correctly
"_twitter_profile" => "your_tweeter_profile_name",										// twitter profile
"_twitter_tweets" => 3,															// how many tweets to load
"_twitter_cache_life" => 15,												// twitter cache life in minutes
"_twitter_cache_path" => "lib/cache/",							// twitter cache path
"_twitter_cache" => 1,															// enables / disables twitter cache
"_dt2" => "d M Y",
"templates" => "templates/",
"file_ext" => ".html"

/*
functions (not added here)
those functions are enhanced versions of basic functions, to try this script you can just take :
_fs = file_get_contents
_fw = file_put_contents
duration = a function to return a number of seconds into years, months, days, hours, minutes, seconds notation
*/

If you want to implement it as javascript, you can use the url:
http://twitter.com/statuses/user_timeline/”.$profile.”.json?callback=x&count=”.$tweets

where the callback is the function where the json data will be sent to.

1 Comment :, , , , , more...

json decode fails on non utf-8

by z3n on Mar.16, 2010, under Coding, Tips & Hints

Problem:

When sending a non utf-8 string as json, the decoding fails.

Solution:

PHP works as utf-8 as default, since i’m using strings with accents (áéíóú..) those are taken as iso-8859-1. Client-side script will not send as utf-8, not even if you force it, so the best solution is convert the json object’s encoding. You may also want to encode your string as plain chars (I use base64) to avoid issues with IE.

Code would look like this:

$json=json_decode(iconv(‘ISO-8859-1′,’UTF-8′,base64_decode($input)),true);

If you’re working with different charsets just change the iso-8859-1, remember that if you’re working with multibyte chars, such as japanese, chinese, etc, you will need to use the mb functions instead.

Sources:

Pablo Viquez (A solution pretty much like mine but for sending data instead)

2 Comments :, , , , more...

Fatal error: Cannot use object of type stdClass as array (php json_decode)

by z3n on Feb.17, 2010, under Coding, Notes, Tips & Hints

Problem:

$var=json_decode($_POST['something']);

echo $var['value'];

returns error: Fatal error: Cannot use object of type stdClass as array

Solution:

echo $var->value;

2 Comments :, , , , more...

The Ampersand (&) XML Problem

by z3n on Sep.26, 2009, under Coding

Problem:

Having ampersands (&) on a xml makes it non-compliant, causing errors on IE.

Solution:

I’ve been looking on this issue for a while, although I had the answer already I wanted an alternate. One said that you could turn the & into & html entity or it’s ASCII code, but this just gets into another issue, since the & will still there – & & – In my case I had accents encoded as html entities, like áéíóú, which must be encoded (at least on my project) as entities to be passed as xml/json/etc. Other people noted that it’s possible to have specific entities declared on the html header, although this is a drawback, because xml will become quite big if you have too many different entities AND you will have to redeclare them on every reply.

None of the solutions I’ve found were good, so I’m posting mine.

A simple base64 encode would resolve the issue, and you only need to do it on replies, making things easier, so you send as base64 and the user with a little javascript decodes it back.

Base64 Javascript Source Code:

  1. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  2.  
  3. function _enc(input) {
  4.    var output = "";
  5.    var chr1, chr2, chr3;
  6.    var enc1, enc2, enc3, enc4;
  7.    var i = 0;
  8.    do {
  9.       chr1 = input.charCodeAt(i++);
  10.       chr2 = input.charCodeAt(i++);
  11.       chr3 = input.charCodeAt(i++);
  12.  
  13.       enc1 = chr1 >> 2;
  14.       enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  15.       enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  16.       enc4 = chr3 & 63;
  17.  
  18.       if (isNaN(chr2)) {
  19.          enc3 = enc4 = 64;
  20.       } else if (isNaN(chr3)) {
  21.          enc4 = 64;
  22.       }
  23.  
  24.       output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  25.          keyStr.charAt(enc3) + keyStr.charAt(enc4);
  26.    } while (i < input.length);
  27.    
  28.    return output;
  29. }
  30.  
  31. function _dec(input) {
  32.  if (input == "NULL") { return ""; }
  33.    var output = "";
  34.    var chr1, chr2, chr3;
  35.    var enc1, enc2, enc3, enc4;
  36.    var i = 0;
  37.  
  38.    // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
  39.    input = input.replace(/[^A-Za-z0-9\+\/\=]/g|>, "");
  40.  
  41.    do {
  42.       enc1 = keyStr.indexOf(input.charAt(i++));
  43.       enc2 = keyStr.indexOf(input.charAt(i++));
  44.       enc3 = keyStr.indexOf(input.charAt(i++));
  45.       enc4 = keyStr.indexOf(input.charAt(i++));
  46.  
  47.       chr1 = (enc1 << 2) | (enc2 >> 4);
  48.       chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  49.       chr3 = ((enc3 & 3) << 6) | enc4;
  50.  
  51.       output = output + String.fromCharCode(chr1);
  52.  
  53.       if (enc3 != 64) {
  54.          output = output + String.fromCharCode(chr2);
  55.       }
  56.       if (enc4 != 64) {
  57.          output = output + String.fromCharCode(chr3);
  58.       }
  59.    } while (i < input.length);
  60.  
  61.    return output;
  62. }
Leave a Comment :, , , , , , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!