Search

Parsing data from twitter search.twitter.com/search.json?query=

Parsing data from twitter search.twitter.com/search.json?query=

Followers of this blog will know that I have been playing with twitter and an arduino.

I would like to document my method of parsing twitter for data.

PHP code follows, but any language that can parse json data will be fine.

< ?php /* This code will parse twitter for a search string from a particular twitter handle passed variables: username twitter username q search string count Maximum number of results to return since_id This can initially be empty, it gets populated by the json resultThis script will return the following parseable string: "tweet messagehttp://refresh.urlusername" After the first pass, you can simply send the information in the tags which will only return any new results.*/ $host = "http://search.twitter.com"; $filename = "/search.json"; $username = (isset($_GET['username']) ? stripslashes($_GET['username']) : "gregoryfenton"); $query = (isset($_GET['query']) ? stripslashes($_GET['query']) : "arduino");$opts = array('http' => array(
‘method’=>”GET”,
‘header’=>”Accept-language: en\r\n”
));
$context = stream_context_create($opts);

$search = isset($_GET[‘q’]) ? stripslashes($_GET[‘q’]) : “candy4greg”;
$search = str_replace(” “, “%20”, $search);
$count = isset($_GET[‘count’]) ? stripslashes($_GET[‘count’]) : “1”;
$since = isset($_GET[‘since_id’]) ? stripslashes($_GET[‘since_id’]) : “”;

$a = “$host$filename?” . ($search == “” ? “” : “q=$search”) . ($count == “” ? “” : “&count=$count”) . ($since == “” ? “” : “&since_id=$since”);
echo “$a\n”;
$json = file_get_contents($a, false, $context);

$obj = json_decode($json, true);
$tweet = $obj[‘results’][0][‘text’];
$refresh = $obj[‘refresh_url’];
$user = $obj[‘results’][0][‘from_user’];

echo “searching for $search\ncount: $count\nsince: $since\n”;
echo “”;
echo “$tweet”;
if($refresh != “”)
echo “$refresh”;
if($user != “”)
echo “$user”;
echo “”
?>

Related posts

Leave a Comment