Using Yahoo Query Language (YQL) With PHP

It is really interesting to access webservices of yahoo using SQL like comands called YQL, Yahoo Query Language.

YQL webservice has pre-defined tables for Flickr, MyBlogLog and some other webservices.
Moreover, an user-defined Open Data Table can be created to access data sources of webservices other than Yahoo!.

The output can be recieved in either XML or JSON format.
We can pass the YQL statement as a URL parameter, for example ( one found on the online tutorial ) :

XML format

http://query.yahooapis.com/v1/public/yql?q=SELECT * FROM flickr.photos.search WHERE text=”Cat”

JSON format

http://query.yahooapis.com/v1/public/yql?q=SELECT * FROM flickr.photos.search WHERE text=”Cat”&format=json

How to use in PHP

Zend_Rest_Client object can be used in zend framework as mentioned below. Here the xml document returned will be parsed and converted to Zend_Rest_Client_Response object.

$client = new Zend_Rest_Client('http://query.yahooapis.com/v1/public/yql');

$client->q('SELECT * FROM flickr.photos.search WHERE text="Cat"');

$result = $client->get();

foreach ($result->photo as $val) {
    

     /*Value of each attribute can be accessed under the node */

    echo "farm ->".$val['farm']."
"; echo "id ->".$val['id']."
"; }

Similarly, in PHP, we can use the method simplexml_load_file() which will return a parsed xml document converted into SimpleXML object.

$xml = simplexml_load_file('http://query.yahooapis.com/v1/public/yql?q=SELECT * FROM flickr.photos.search WHERE text="Cat"');

$results = $xml->results; /* Accessing parent node  */

foreach ($results->photo as $val) {

     /*Value of each attribute can be accessed under the node */

   echo "farm ->".$val['farm']."
"; echo "id ->".$val['id']."
"; }

An online console is also present to run and test the YQL at the below mentioned URL.

http://developer.yahoo.com/yql/console/

More details can be found at

http://developer.yahoo.com/yql/guide/index.html

150 150 Burnignorance | Where Minds Meet And Sparks Fly!