Get Google News as JSON by Parsing rss feed

Standard

Google-News-Nuhil
As you know already that, Google News search API has been deprecated few years ago. Still developers need to have Google news as an usable format like JSON for different purpose & development platforms.

Google still provides the news service but in rss format. So, we can have those data for using just by parsing and reformatting them. I wrote a very small php class which will first search  news on Google by specific keywords and load the XML. Then it will parse the XML carefully to dissect parts of news & finally will provide a formatted JSON data set.

As of JSON, all knows that how universal this data format is to implement on several software development platforms. Hope this tiny class help some one 🙂

The class file:

<?php
 **
 * Google-News feed parser and JSON provider Class
 *
 * @package None
 * @author Nuhil Mehdy <nuhil@nuhil.net>
 */
class GoogleNews {

    public $searchQuery = 'Good News';

    public function __construct ($searchQuery) {
            if(!empty($searchQuery)) {
                    $this->searchQuery = $searchQuery;
            }

            $this->numberOfNews = 5;
    }

    public function __toString() {
            return $this->getNews();
    }

    public function setSearchQuery($searchQuery) {
            if(!empty($searchQuery)) {
                    $this->searchQuery = $searchQuery;
            }
    }

    public function setNumberOfNews ($numberOfNews) {
            if(!empty($numberOfNews)) {
                    $this->numberOfNews = (int) $numberOfNews;
            }
    }

    public function getNews () {
            return $this->processNews();
    }

    private function processNews() {
            $loadXml = simplexml_load_file(urlencode('http://news.google.com/news?q='.$this->searchQuery.'&num='.$this->numberOfNews.'&output=rss'));

            $news = array();

            $i = 0;
            foreach ($loadXml->channel->item as $item)
            {
                preg_match('@src="([^"]+)"@', $item->description, $match);
                $newsSections = explode('</pre>
', $item->description);

 $news[$i]['title'] = (string) $item->title;
 $news[$i]['image'] = $match[1];
 $news[$i]['link'] = (string) $item->link;
 $news[$i]['news_source'] = strip_tags($newsSections[1]);
 $news[$i]['short_story'] = strip_tags($newsSections[2]);

 $i++;
 }

 $result = array('news' => $news, 'status' => '200', 'message' => 'OK');

 return json_encode($result);
 }

}
?>

Example usage:

<?php
include('news.php'); 
$news = new GoogleNews(); 
$news->setSearchQuery('Bangladesh');
$news->setNumberOfNews('10');
echo $news->getNews();
?>

You will find this source code on github also. Feel free to use and or fork.

How to get formatted address by Google Maps API

Standard

This is an example procedural steps for getting level wised (City, State/Division, Country, Latitude, Longitude) geolocation from a given address string.

This example can be implemented on a input form where user will put his physical address and your system will store the additional information for further use like for generating location based query corresponding to that address. For example your system can suggest him near by places using his latitude, longitude by calling another google maps API.

<?php
    $address = urlencode('Bogra,Bangladesh');

    $url = "http://maps.google.com/maps/api/geocode/json?address=".$address."&sensor=false&language=en";
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_GET, true);
    $response = curl_exec($ch);
    curl_close($ch);
    
    if( $response ) {
        $res    = json_decode( $response, true );        
        
        $locationDetail = array();
        
        if( (isset ($res['status'])) && ($res['status'] == 'OK') ) {
            
            /* 
             * Format address whether it has more than one admin level
             */
            $address_components = $res['results'][0]['address_components'];
            $geometry = $res['results'][0]['geometry'];
            $address = array();
            
            foreach ($address_components as $components):
                    $address[$components['types'][0]] = array ('short_name' => $components['short_name'], 'long_name' =>  $components['long_name']);
            endforeach;  
            
            $address['lat'] = (String) $geometry['location']['lat'];
            $address['lng'] = (String) $geometry['location']['lng'];            
            
            $locationDetail['city'] = (($address['locality']['long_name'] != 'false') && ($address['locality']['long_name'] != '')) ? $address['locality']['long_name'] : 'Not Found';
            $locationDetail['state'] = (($address['administrative_area_level_1']['short_name'] != 'false') && ($address['administrative_area_level_1']['short_name'] != '')) ? $address['administrative_area_level_1']['short_name'] : 'Not Found';
            $locationDetail['state_name'] = (($address['administrative_area_level_1']['long_name'] != 'false') && ($address['administrative_area_level_1']['long_name'] != '')) ? $address['administrative_area_level_1']['long_name'] : 'Not Found';
            $locationDetail['country'] = (($address['country']['short_name'] != 'false') && ($address['country']['short_name'] != '')) ? $address['country']['short_name'] : 'Not Found';
            $locationDetail['country_name'] = (($address['country']['long_name'] != 'false') && ($address['country']['long_name'] != '')) ? $address['country']['long_name'] : 'Not Found';
            
            $locationDetail['lat'] = (($address['lat'] != 'false') && ($address['lat'] != '')) ? $address['lat'] : 'Not Found';
            $locationDetail['lon'] = (($address['lng'] != 'false') && ($address['lng'] != '')) ? $address['lng'] : 'Not Found';
        }
    }

    var_dump($locationDetail);

The output should be:

array(7) {
  ["city"]=>
  string(5) "Bogra"
  ["state"]=>
  string(8) "Rajshahi"
  ["state_name"]=>
  string(8) "Rajshahi"
  ["country"]=>
  string(2) "BD"
  ["country_name"]=>
  string(10) "Bangladesh"
  ["lat"]=>
  string(5) "24.85"
  ["lon"]=>
  string(10) "89.3666667"
}

Using Google Web Fonts in Webpages

Standard

Using Google web fonts is very easy and it can give your text content a smart and beautiful look. Just simply add your chosen font like the example below and see the change.

About Google Web Fonts
A web with web fonts is more beautiful, readable, accessible and open.
Google Web Fonts makes it quick and easy for everyone to use web fonts, including professional designers and developers. We believe that everyone should be able to bring quality typography to their web pages and applications. (From Google)

<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Codystar' rel='stylesheet' type='text/css'>
<style type="text/css">
    h1, h2, h3, h4 {
    font-family: 'Codystar', cursive;
    text-align: center;
    }
</style>
</head>
<body>
    <h1>Using google Web Font</h1>
    <h4>Pretty easy to use and output is really cool</h4>
</body>
</html>