| Hacking with PHP |
 |
2012-05-16 |
 |
 |

29 |
 |
 |
Take a pinch of RSS
<?php
$url = 'http://buzz.yahoo.com/feeds/buzzoverl.xml';
$xml = simplexml_load_file($url);
if($xml) {
foreach($xml->channel->item as $item) {
$ret[(string)$item->title] = (string)$item->link;
}
echo "<pre>"; print_r($ret); echo "</pre>";
} else echo "Can't get to Yahoo!";
?>
Output
Array
(
[1. Facebook] => http://search.yahoo.com/search?p=facebook&cs=bz
[2. YouTube] => http://search.yahoo.com/search?p=youtube&cs=bz
[3. Emma Watson] => http://search.yahoo.com/search?p=emma+watson&cs=bz
[4. Tea Leoni] => http://search.yahoo.com/search?p=tea+leoni&cs=bz
[5. Raven Symone] => http://search.yahoo.com/search?p=raven+symone&cs=bz
[6. Elizabeth Taylor] => http://search.yahoo.com/search?p=elizabeth+taylor&cs=bz
[7. Mel Gibson] => http://search.yahoo.com/search?p=mel+gibson&cs=bz
[8. Megan Fox] => http://search.yahoo.com/search?p=megan+fox&cs=bz
[9. Airline Baby Ban] => http://search.yahoo.com/search?p=airline+baby+ban&cs=bz
[10. Bam Margera] => http://search.yahoo.com/search?p=bam+margera&cs=bz
[11. Casey Anthony] => http://search.yahoo.com/search?p=casey+anthony&cs=bz
[12. Brian Austin Green] => http://search.yahoo.com/search?p=brian+austin+green&cs=bz
[13. Tia Mowry] => http://search.yahoo.com/search?p=tia+mowry&cs=bz
[14. Maria Sharapova] => http://search.yahoo.com/search?p=maria+sharapova&cs=bz
[15. Toronto International Film Festival] => http://search.yahoo.com/search?p=toronto+international+film+festival&cs=bz
)
Add a spoonful of REST
<?php
$imgs='http://api.search.yahoo.com/ImageSearchService/V1/imageSearch';
$news='http://api.search.yahoo.com/NewsSearchService/V1/newsSearch';
foreach($ret as $key=>$link) {
$url = $imgs . "?query=$key&appid=RESTDemo";
$obj = simplexml_load_file($url);
...
$url = $news . "?query=$key&appid=RESTDemo";
$obj = simplexml_load_file($url);
}
?>
A thimble of gradeschool math
And we end up with something like this
By the way, throwing a cache layer between you and whatever remote service you are
accessing tends to be a good idea. In our case we can do it like this:
<?php
$tmp = '/tmp/'.md5($q);
if(!file_exists($tmp) || filemtime($tmp) < (time()-7200)) {
$stream = fopen($url,'r');
$tmpf = tempnam('/tmp','YWS');
file_put_contents($tmpf, $stream);
fclose($stream);
rename($tmpf, $tmp);
}
$obj = simplexml_load_file($tmp);
?>