Creating simple Web-Widget using PHP and Javascript

Most of the website are sharing the data in forms of API, Feeds and Widget.
Today we will elaborate, how to create simple Widget using PHP and htaccess.

Before creating Web-Widget, we will get know few things about Widget.

What is Widget ?
Widget is a small application with methods, which share information from one website to another.

First we will create widget.php files, its our server side file.
Which will accept three parameters like width, height and border to display feed display.

// accessing the parameters from the url
$w = (isset($_GET["w"])) ? $_GET["w"] : 400;
$h = (isset($_GET["h"])) ? $_GET["h"] : 90;
$b = (isset($_GET["b"])) ? 1 : 0 ;

// accessing feed date using simplexml_load function 
$data = simplexml_load_file("");

// getting the array count
$rowCnt = count($data->channel->item);

// assigning arrays to an varaible
$arrRow = $data->channel->item;

// checking if the parameters is 0 or 1, which will determine the border style into div tag
$border = ($b>0) ? "border:".$b."px solid #a1a1a1;overflow:auto;" : ""; 

// concating string into loop to display the widget data
$str = "<div id=\"divWidget\" style=\"width:".$w."px;height:".$h."px;".$border."\">";
for($iRows=0;$iRows<$rowCnt;$iRows++) { 
$str .= "<a href=\"".$arrRow[$iRows]->link."\" target=\"_blank\">".$arrRow[$iRows]->title."</a><br />";
$str .= "</div>";

// binding values into Javascript
echo "document.writeln('".$str."');";

Next is our widget.html, which is our client side file.

<script src="widget.js?w=250&h=100&b=1"></script>


Finally .htaccess will rewrite the url, from widget.php to widget.js

RewriteEngine on
RewriteRule ^widget.js(.*)$ widget.php

[ Download ] | [ Demo ]