Wednesday, 6 April 2011

Using YQL with PHP

I've just started to look into YQL. It looks very powerful but some of the videos an tutorials are a bit dry. There are some missing links which I'm hoping to expose in how to implement with PHP. It should be possible to use YQL for your applications very easily, but at the moment I'm finding my way around it. Part of the problem seems to be around not knowing the structure of the returned JSON before you have to present it. We'll see. Below is an example of calling some YQL on a single web page and displaying the paragraphs within it. I call a very simple PHP GET using CURL. Then I loop through the resulting JSON object until I reach the paragraphs.
Good luck!


<?php
$api = 'http://query.yahooapis.com/v1/public/yql?q=';
$query = 'select * from html where url="http://www.stream-idc.net/"';
$params = '&format=json';

$session = curl_init($api.urlencode($query).$params);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);  
$json = curl_exec($session);
curl_close($session);
$yqlObj =  json_decode($json);

if(!is_null($yqlObj->query->results))
{
foreach($yqlObj->query->results->body->p as $bodyContent)
{
echo $bodyContent->{'content'};
}
}
?>

No comments:

Post a Comment