XMLToArray Generator Class


Here is a PHP class that read xml file and make an array. First save this class file as xmltoarray.php and then create an object like new XmlToArray($xml_data). Finally just call createArray() function. It will be helpful when we don’t want to use database or any kind of web services. Bellow i have given full source code. I think it will be helpful.

<?
/**
* XMLToArray : Converting XML into Array
*
* @author  :  MA Razzaque Rupom <rupom_315@yahoo.com>, <rupom.bd@gmail.com>
*             Moderator, phpResource (http://groups.yahoo.com/group/phpresource/)
*             URL: http://www.rupom.info
* @version :  1.0
* @date       11/03/2006
* Purpose  :  Creating Hierarchical Array from XML Data
*/

class XmlToArray
{

private $xml=”; //To use in PHP4, use “var”

/**
* Default Constructor
* @param $xml = xml data
* @return none
*/

function XmlToArray($xml)
{
$this->xml = $xml;
}

/**
* _struct_to_array($values, &$i)
*
* This adds the contents of the return xml into the array for easier processing.
* Recursive, Static
*
* @access    private
* @param    array  $values this is the xml data in an array
* @param    int    $i  this is the current location in the array
* @return    Array
*/

function _struct_to_array($values, &$i)
{
$child = array();

if (isset($values[$i][‘value’]))
{
array_push($child, $values[$i][‘value’]);
}

while ($i++ < count($values))
{
switch ($values[$i][‘type’])
{
case ‘cdata’:
array_push($child, $values[$i][‘value’]);
break;

case ‘complete’:
$name = $values[$i][‘tag’];
if(!empty($name))
{
$child[$name]= ($values[$i][‘value’])?($values[$i][‘value’]):”;

if(isset($values[$i][‘attributes’]))
{
$child[$name] = $values[$i][‘attributes’];
}
}
break;

case ‘open’:
$name = $values[$i][‘tag’];
$size = isset($child[$name]) ? sizeof($child[$name]) : 0;
$child[$name][$size] = $this->_struct_to_array($values, $i);
break;

case ‘close’:
return $child;
break;
}
}
return $child;

}//EO _struct_to_array

/**
* createArray($data)
*
* This adds the contents of the return xml into the array for easier processing.
*
* @access    public
* @param    string    $data this is the string of the xml data
* @return    Array
*/
function createArray()
{
$xml    = $this->xml;
$values = array();
$index  = array();
$array  = array();
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parse_into_struct($parser, $xml, $values, $index);
xml_parser_free($parser);
$i = 0;
$name = $values[$i][‘tag’];
$array[$name] = isset($values[$i][‘attributes’]) ? $values[$i][‘attributes’] : ”;
$array[$name] = $this->_struct_to_array($values, $i);
return $array;
}//createArray

}//EO Class XmlToArray

?>

<?php

/**
* phpResourceRssFeed : phpResource Feeds for Your Site
*
* @author  :  MA Razzaque Rupom <rupom_315@yahoo.com>, <rupom.bd@gmail.com>
*             Moderator, phpResource (http://groups.yahoo.com/group/phpresource/)
*             URL: http://www.rupom.info
* @version :  1.0
* @date       11/03/2006
*/

?>
<title>phpResource Feeds for Your Site</title>
<?php

require_once(“XmlToArray.class.php”);

$xml_data = file_get_contents(“http://rss.groups.yahoo.com/group/phpresource/rss&#8221;);

//Creating Instance of the Class
$xmlObj    = new XmlToArray($xml_data);

//Creating Array
$arrayData = $xmlObj->createArray();

$rssData = array();

$rssData = $arrayData[‘rss’][‘channel’][0][‘item’];

$colors = array(‘#CCCCCC’,’#f5f5f5′);

$numColors = count($colors);

if(!empty($rssData))
{
?>
<table align=”left”>
<tr>
<td>&nbsp;</td>
</tr>
<tr bgcolor=”#6699CC”>
<td colspan=”2″><font size=”5″><b>Latest Posts of <a href=”http://groups.yahoo.com/group/phpresource/”>phpResource Group</a></b></font></td>
</tr>
<tr>
<td colspan=”2″>&nbsp;</td>
</tr>
<?php
$i = 0;
foreach($rssData as $i=>$v)
{

$title   = $v[‘title’];
$link    = $v[‘link’];
$author  = $v[‘author’];
$pubDate = $v[‘pubDate’];
$desc    = $v[‘description’];

?>

<tr bgcolor=”<?=$colors[$i%$numColors];?>”>
<td><a href=”<?=$link?>”><font size=”4″><?=$title?></font></a><br />&nbsp;&nbsp;&nbsp;On <?=$pubDate?> By <b><?=$author?></b></td>
</tr>
<tr>
<td>
<?php

$desc = wordwrap( $desc, 72, “<br>”);
echo “$desc …. “;

//echo $desc.’ <b>…</b> ‘;
?>
<br />
<a href=”<?=$link?>”>Read More…</a>
</td>
</tr>
<tr>
<td>&nbsp;</td>
</tr>
<?php
$i++;
}
}

function dBug($arr)
{
echo “<PRE>”;
print_r($arr);
echo “</PRE>”;
}
?>

<tr bgcolor=”#6699CC”>
<td><a href=”http://groups.yahoo.com/group/phpresource/join/”><font size=”5″>Click Here to Join phpResource</font></a></td>
</tr>

</table>

User define PHP date function


Sometimes we need to display date in different format as user requirements. Here some PHP user define date function i have used. I think it will be helpful for PHP professionals. As you can see in my all example there are tons of different formats that can be used in the date feature.

<?php
/**
* mysql::cDateMySQL2Br()
* convert date from YYYY/MM/DD to DD/MM/YYYY
*/
function cDateMySQL2Br($dt) {

if (strlen($dt) > 10) $dt = substr($dt,0,10); //despreza a hora

if (strlen($dt) == 10) {
$nYear = substr($dt,0,4); $nMonth = substr($dt,5,2); $nDay = substr($dt,8,2);
if (checkdate($nMonth, $nDay, $nYear)) $sDate = “$nDay/$nMonth/$nYear”;
}
return $sDate;
}

/**
* mysql::cDateTimeMySQL2Br()
* convert date time from YYYY/MM/DD HH:MM:SS to DD/MM/YYYY HH:MM:SS
*/
function cDateTimeMySQL2Br($dt) {

if (strlen($dt) > 10) {
$tm = substr($dt,11, strlen($dt)-11);
$dt = substr($dt,0,10);
}

if (strlen($dt) == 10) {
$nYear = substr($dt,0,4); $nMonth = substr($dt,5,2); $nDay = substr($dt,8,2);

if (checkdate($nMonth, $nDay, $nYear)) $sDate = “$nDay/$nMonth/$nYear”;
}
if ($tm != “” && $tm != “00:00:00”) $sDate = “$sDate $tm”;
return $sDate;
}

/**
* mysql::cDateBr2MySQL()
* convert date from DD/MM/YYYY to YYYY/MM/DD
*/
function cDateBr2MySQL($dt) {

if (strtoupper($dt) == “NULL”) $sDate = $dt;
if (strlen($dt) > 10) $dt = substr($dt,0,10); //despreza a hora

if (strlen($dt) == 10) {
if ($debug) echo “Converting date: Portuguese[$dt] for “;
$nYear = substr($dt,6,4); $nMonth = substr($dt,3,2); $nDay = substr($dt,0,2);
if ($debug) echo “MySQL[$nYear/$nMonth/$nDay] <br>\n\n”;

//if (checkdate($nMonth, $nDay, $nYear))
$sDate = “$nYear/$nMonth/$nDay”;
} else {
if ($debug) echo “Date format inválid [$dt]. Use dd/mm/YYYY <br>\n\n”;
}
return $sDate;
}

/**
* mysql::cDateTimeBr2MySQL()
* convert date time from DD/MM/YYYY HH:MM:SS to YYYY/MM/DD HH:MM:SS
*/
function cDateTimeBr2MySQL($dt) {

if (strtoupper($dt) == “NULL”) $sDate = $dt;
if (strlen($dt) > 10) {
$tm = substr($dt,11,strlen($dt)-11);
$dt = substr($dt,0,10);
}

if (strlen($dt) == 10) {
if ($debug) echo “Converting date: Portuguese[$dt] for “;
$nYear = substr($dt,6,4); $nMonth = substr($dt,3,2); $nDay = substr($dt,0,2);
if ($debug) echo “MySQL[$nYear/$nMonth/$nDay] <br>\n\n”;

//if (checkdate($nMonth, $nDay, $nYear))
$sDate = “$nYear/$nMonth/$nDay”;
} else {
if ($debug) echo “Date format inválid [$dt]. Use dd/mm/YYYY <br>\n\n”;
}

if ($tm != “” && $tm != “00:00:00”) $sDate = “$sDate $tm”;

return $sDate;
}

/**
* mysql::fullDateFormat()
* convert date from YYYY-MM-DD to May 3, 2008
*/
function fullDateFormat( $value ){
$d = explode(“-“, $value);
$cdate = date (“F j, Y”, mktime (0,0,0,$d[1],$d[2],$d[0]));
return $cdate;
}

/**
* mysql::panFormatDate()
* convert date from %Y-%m-%d %H:%M:%S to Monday, 17 March 2008
*/
function panFormatDate( $date, $format=””, $offset=NULL ){
if ( $format == ” ) {
// %Y-%m-%d %H:%M:%S
$format = “%A, %d %B %Y”;
}
if ( is_null($offset) ) {
$offset = 0;
}
if ( $date && ereg( “([0-9]{4})-([0-9]{2})-([0-9]{2})[ ]([0-9]{2}):([0-9]{2}):([0-9]{2})”, $date, $regs ) ) {
$date = mktime( $regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1] );
$date = $date > -1 ? strftime( $format, $date + ($offset*60*60) ) : ‘-‘;
}
return $date;
}
?>

Handy pagination PHP class with MySql


What if you have a table with a thousand rows, and you want to allow the user to browse through the entire table. Simply listing all the records in that table would not be a good idea. Instead you should break the table up into smaller “chunks” and allow the user to navigate through theses “chucks”. This is what pagination does, it allows you to break up large result sets from a database query, and present it to the user in a more manageable way.

As your database grows, showing all the results of a query on a single page is no longer practical. This is where pagination comes in handy. You can display your results over a number of pages, each linked to the next, to allow your users to browse your content in bite sized pieces.

This css put your css file or your file head section

<style type=”text/css”>
a.linksitem:link, a.linksitem:visited{
font-family:Arial, Helvetica, sans-serif;
font-size:12px;
text-decoration:none;
font-weight:normal;
width:auto;
height:20px;
border:1px solid #75ABEA;
background-color:#FFFFFF;
color:#2E6AB1;
padding-right:5px;
padding-left:5px;
}
a.linksitem:hover{
border:1px solid #2E6AB1;
color:#000000;
}
.selectedlinks{
border:1px solid #2E6AB1;
background-color:#2E6AB1;
color:#FFFFFF;
font-weight:800;
padding-right:5px;
padding-left:5px;
}
</style>

This is the PHP class for pagination

<?php
class pagination{

var $p=1, $max_r, $limits;
var $count_all=0, $sql, $total, $table, $totalres, $totalpages;
var $r, $i;
var $show=10;

function connect($host,$username,$password,$name){
//—–connect mysql—–//
$connectect = mysql_connect($host, $username, $password) or die(mysql_error());
$selected = mysql_select_db($name) or die(mysql_error());
}

function setMax($max_r){

$this->p = $_GET[‘p’];
$this->max_r = $max_r;

if(empty($this->p))
{
$this->p = 1;
}
$this->limits = ($this->p – 1) * $this->max_r;
}

function setData($table){

$this->table = $table;
$this->sql = “SELECT * FROM “.$this->table.” LIMIT “.$this->limits.”,”.$this->max_r.””;
$this->sql = mysql_query($this->sql) or die(mysql_error());
$this->total = “SELECT * FROM “.$this->table.””;
$this->totalres =  mysql_query($this->total) or die(mysql_error());
$this->count_all = mysql_num_rows($this->totalres);
$this->totalpages = ceil($this->count_all / $this->max_r);
}

function display($titlebar, $rowsitem){
echo “<b>Total Values(s):</b>”.$this->count_all.”<br><br>”;
echo “<b>Page:</b> “.$this->p.”<br>”;
$fields=mysql_num_fields($this->totalres);
echo ‘<table border=”1″ width=”100%” cellspacing=”0″ cellpadding=”4″><tr>’;
for ($i=0; $i < mysql_num_fields($this->sql); $i++) //Table Header
{
print “<th class=’titlebar’>”.mysql_field_name($this->sql, $i).”</th>”;
}
echo “</tr>”;
while ($row = mysql_fetch_row($this->sql))
{
echo “<tr>”;
for ($f=0; $f < $fields; $f++)
{
echo “<td class=’rowsitem’>$row[$f]</td>”;
}
echo “</tr>\n”;
}
echo “</table><p>”;
}

function displayLinks($show){

$this->show = $show; // How many links to show
echo “<br><br>”;
if($this->p > 1) // If p > then one then give link to first page
{
echo “<a class=’linksitem’ href=?p=1> First </a>&nbsp;”;
}
else{ // else show nothing
echo “”;
}
if($this->p != 1){ // if p aint equal to 1 then show previous text
$previous = $this->p-1;
echo “<a class=’linksitem’ href=?p=$previous> Previous </a>&nbsp;”;
}
else{ //else show nothing
echo “”;
}
for($i =1; $i <= $this->show; $i++) // show ($show) links
{

if($this->p > $this->totalpages){ // if p is greater then totalpages then display nothing
echo “”;
}
else if($_GET[“p”] == $this->p){ //if p is equal to the current loop value then dont display that value as link
echo “<span class=’selectedlinks’>”.$this->p.”</span>”;
}
else{
echo ” <a class=’linksitem’ href=?p=”.$this->p.”>”.$this->p.”</a>”; // else display the rest as links
}
$this->p++; //increment $p
}
echo “…..”; // display dots

if($_GET[“p”] == $this->totalpages){// if page is equal to totalpages then  dont display the last page at the end of links
echo “”;
}
else // else display the last page link after other ones
{
echo “<a class=’linksitem’ href=?p=”.$this->totalpages.”>”.$this->totalpages.”</a>”;
}
if($_GET[“p”] < $this->totalpages)// if p is less then total pages then show next link
{
$next = $_GET[“p”] + 1;
echo “&nbsp;<a class=’linksitem’ href=?p=$next> Next </a>”;
}
echo “<br><br>”;
}
}
?>

Now call pagination class there you may use pagination

<?php
$page= new pagination; //Create object
$page->connect(“servername”,”username”,”password”,”batabasename”); //Create database connection
//$page->connect(“localhost”,”root”,””,”test”); // example
$page->setMax(10); //Number of items display
$page->setData(“tablename”); //Tables name here
$page->display(rana, test); //Display data
$page->displayLinks(9); //Display links
?>

Download code

No Right Click


No Right Click – Disable the right click on your pages to prevent users from “borrowing” images from your site and viewing your page source!

Ever wanted to prevent users from “borrowing” images from your site through right-clicking them and “save image as…” or right-clicking the page and viewing your page source? The No Right Click will disable the right click on your page in just a few clicks. No programming knowledge needed!

Protect the content of your Web page by preventing others from viewing your source code!

Simply add the following code to the <BODY>  section of your web page (Press Ctrl C after selecting code to copy it):

<script language=JavaScript>
<!–
var message=”This website and it’s contents are owned and licensed by https://ranawd.wordpress.com.\nAll contents are copyrighted and are not available for download and/or use on any other site.\n\nAll Rights Reserved. © 2007-2008 https://ranawd.wordpress.com&#8221;;
///////////////////////////////////
function clickIE4(){
if (event.button==2){
alert(message);
return false;
}
}
function clickNS4(e){
if (document.layers||document.getElementById&&!document.all){
if (e.which==2||e.which==3){
alert(message);
return false;
}
}
}
if (document.layers){
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById){
document.onmousedown=clickIE4;
}
document.oncontextmenu=new Function(“alert(message);return false”)
// –>
</script>

Javascript validation check


There ate two javascript validation function i have made.

First one check empty field using id. We may use field id by an array as bellow. This function check empty field and if found empty field then focus that field also. We may use here another condition like email, phone number check. I think this will be reduce line number of code and time also.
Example:
<form method=”post” action=”<?=$_SERVER[‘PHP_SELF’]?>” onSubmit=”return checkClientForm();”>
<input type=”text” name=”name” id=”name” value=”” tabindex=”1″ /><br />
<input type=”text” name=”title” id=”title” value=”” tabindex=”2″ /><br />
<input type=”text” name=”description” id=”description” value=”” tabindex=”3″ /><br />
<input type=”submit” name=”submit” value=”Save” tabindex=”4″ />
</form>

Second one check file type like image. We may use this function by onchange element. If the file type dose not match then this will give a alert and clear the field also.

Example:
<input type=”file” name=”image” id=”image” value=”” onchange=”checkPhoto()” />

<script language=”javascript” type=”text/javascript”>
function checkClientForm(){
var cont;
var allid = new Array(“name”,”title”,”description”); //you may add more
var msg;
for (var i=0; i<=allid.length-1; i++){
cont=document.getElementById(allid[i]).value;
if(cont.length==0){
alert(“You should fill the required fields properly”);
document.getElementById(allid[i]).focus();
return false;
}
}
return true;
}

function checkPhoto(){
if( (document.getElementById(‘image’).value.split(‘.’)[1]!=’jpg’) && (document.getElementById(‘image’).value.split(‘.’)[1]!=’jpeg’) && (document.getElementById(‘image’).value.split(‘.’)[1]!=’JPG’) && (document.getElementById(‘image’).value.split(‘.’)[1]!=’JPEG’) && (document.getElementById(‘image’).value.split(‘.’)[1]!=’png’) && (document.getElementById(‘image’).value.split(‘.’)[1]!=’PNG’)){ alert(“Sorry, This type of file is not allowed to upload.”); document.getElementById(‘image’).value=”; document.getElementById(‘image’).focus(); return false; }
}
</script>

Write The XML File


Recently I have made a function that write xml file and bring data from mysql database. Its very easy to use. First put this function and call that function after mysql row insert, update or delete. Finally we may use this xml for different purpose. I think it will be helpful for someone.

function xmlfilewrite($xmlfile, $tablename)
{
// Write The XML File
$xmlfile_path= ROOT_PATH.”/”.$xmlfile; // ROOT_PATH like define(‘ROOT_PATH’, $_SERVER[‘DOCUMENT_ROOT’].”/sitename”);
$query_xmlw = “SELECT * FROM $tablename ORDER BY ordering DESC”;
$result_xmlw = mysql_query($query_xmlw);

$xmlstore='<?xml version=”1.0″ encoding=”utf-8″ standalone=”yes”?>’;
$xmlstore .='<images>’;

while($row_xmlw = mysql_fetch_array($result_xmlw)) {
$xmlstore .='<pic><image>’.$row_xmlw[‘image’].'</image>’;
$xmlstore .='<thumbnail>’.$row_xmlw[‘thumbnail’].'</thumbnail>’;
$xmlstore .='<caption>’.$row_xmlw[‘caption’].'</caption>’; //Create XML with caption
$xmlstore .='</pic>’;
}

$xmlstore .='</images>’;
$handle = fopen($xmlfile_path, ‘w’);
fwrite($handle, $xmlstore);
}

$this->xmlfilewrite(‘xmlfile.xml’, ‘tablename’); // write the xml file
?>

Here the MySql table i have used
CREATE TABLE `tablename` (
`id` int(11) NOT NULL auto_increment,
`image` varchar(255) collate latin1_general_ci NOT NULL,
`thumbnail` varchar(255) collate latin1_general_ci NOT NULL,
`caption` varchar(150) collate latin1_general_ci NOT NULL,
`ordering` int(11) NOT NULL default ‘0’,
PRIMARY KEY (`id`)
) ;

And finally create this type XML
<?xml version=”1.0″ encoding=”utf-8″ standalone=”yes”?>
<images>
<pic>
<image>1211873814.jpg</image>
<thumbnail>thumb_1211873814.jpg</thumbnail>
<caption>Test Image</caption>
</pic>
</images>

Bush


One day a man went to a dealer to buy a car. He bought a chevy corvette crossfire for $29,000. When the man was getting back home he tried to start the radio. But it didn’t worked. So he get back to the dealer and got busted for that. Then the dealer said the radio is auto tunned. Whatever channel u want just give the computer a clue and it will fix that for u. So the man tried it by sayin band. Radio went to a channel where james was singing. Then he switched it to adhunik. On the way a car suddenly cut him off frm the back. He said,”Stupid”. The radio turned to another channel where J. W. Bush was giving his speech.