Set frame height dynamically using javascript

Hi Geeks,
As I faced the problem in so many times for Set Iframe height dynamically using javascript or setting the Iframe height as per its content, If we add the fix height to Iframe tag directly then it just show the scrollbar in that height but sometime we don’t want to show the scrollable area in that Iframe then there are so complex situation to set the Iframe height for dynamic content and the height may vary or Iframe on content coming from database or any other source.

Now we don’t know that what exactly the height of iframe due to its dynamic content, I have tried So many solution for it and finally i left the issue and provide static height to Iframe, i tried all DOM related access manipulations and it just failed due to cross origin and CORS violation issues.
But one day for my selfishness in one project i faced same requirement with an Iframe and if i use the Iframe then it was saving my lot of time So i researched for 4-5 hours and finally i got perfect solution for it.
SOLUTION :

We need to implement the channel communication between parent window and Iframe window by passing the messages . It will work for same or cross domain origins

Note : we should have access for the Iframe source page.

we’ll post a message from the Iframe source page having a height value to the client domain
by using following script

<script>

  // all content including images has been loaded
    window.onload = function() {
        // post our message to the parent
        window.parent.postMessage(
            // get height of the content
            document.body.scrollHeight
            // set target domain
            ,"*"
        )
    };
</script>

Now where you are creating Iframe ,Go to that page
Like your Iframe is having like that

<iframe id="MY_IFRAME_ID" width="100%" style="overflow-x:hidden;overflow-y:hidden;" frameBorder="0" 
scrolling="no" src="https://www.my-bla-bla-url.com/my-bla-bla-page.html" ></iframe>

we have putted dummy url and set the style to overflow hidden and set frameborder as 0 .
and passed width as 100% but didn’t passed the height
so for getting calculated the height automatic please put the script as follow

<script>
 // browser compatibility: get method for event 
    // addEventListener(FF, Webkit, Opera, IE9+) and attachEvent(IE5-8)
    var myEventMethod = 
        window.addEventListener ? "addEventListener" : "attachEvent";
    // create event listener
    var myEventListener = window[myEventMethod];
    // browser compatibility: attach event uses onmessage
    var myEventMessage = 
        myEventMethod == "attachEvent" ? "onmessage" : "message";
    // register callback function on incoming message
    myEventListener(myEventMessage, function (e) {
        // we will get a string (better browser support) and validate
        // if it is an int - set the height of the iframe #my-iframe-id
        if (e.data === parseInt(e.data)) 
            document.getElementById('MY_IFRAME_ID;).height = e.data + "px";
    }, false);
 
</script>

This script will recieve the message passed from Iframe source origin and add the height of iframe dynamically .
Note : MY_IFRAME_ID is the id of Iframe we assumed , you can replace it with your Iframe id in Iframe and script both

Please comment below if you have any query related to this post or feature

form validation library in php

Hi Geeks,

Today i am sharing a generic class for

Form validation library in php

&  it also populate if form validation failed. First of all you can download the ‘form validation library in php’ by clicking on following url.

https://github.com/g10dra/form_validation_php/blob/master/class.validation.php

Now in this class you can validate the require,numeric,file-extension,match password & confirm password,validate url and other validation also.

It is having a validation with database like is_unique in mysql database where you need pass the db connection if you want to user is_unique validation.

Step 1: Include & Initialize the class in header or before your form s following:

//include the form validation class//
require 'class.validation.php'; or any of your path where you have save the class

$db_details=array();//array for db details for validation some fields like is_unique from DB.
//pass the varribale dynamic or static

$db_details['db_host']=DB_HOST;
$db_details['db_user']=DB_USER;
$db_details['db_password']=DB_PASS;
$db_details['db_name']=DB_NAME;


$validation= new validation($db_details);

//

Step 2: Create a HTML FORM

we are assuming that we have a form for add/edit ‘Advertise campaign’ form

Read the full comments in code

 

<div class="content-box-large">
			  				<div class="panel-heading">
					            <div class="panel-title">Add / Update Campaign</div>
					          <?php
							  //this is for getting data for edit mode
					            if(isset($_GET['id']) && $_GET['id']!="")
								{
									$query = "SELECT * from tbl_ads WHERE a_id='".$_GET['id']."' ";
									//we have user a database class for retirving the results ,you  can use your own data retrival process
									if( $database->num_rows( $query ) > 0 )
									{
										$_edited_data = $database->get_results( $query );
										$_edited_data=$_edited_data[0];
									}
									else{
										header("location:campaign.php?err=something bad happen !");
									}
								}
								else
								{
									//add time initialize the blank data in edit data varriable ,if we are add action
									$_edited_data=array();
									$_edited_data['ad_name']="";
									$_edited_data['end_url']="";
									$_edited_data['campaign_type']="";
									$_edited_data['dimension']="";
									$_edited_data['is_active']="";
								
								}
								?>
					        </div>
			  				<div class="panel-body">
			  					<form enctype="multipart/form-data" method="post">
								
								<input type="hidden" name="is_post" value="1" />
								<!-- field for detecting if form is submitted or not -->
								
								<input type="hidden" name="edit_id" value="<?php echo (isset($_GET['id']))? $_GET['id'] : "0"; ?>" />
								<!-- field for detecting if form is submitted in edit or add mode -->
								
									<fieldset>
										<div class="form-group">
											<label>Ad Campaign Name</label>
											<input value="<?php echo $validation->set_val("ad_name",$_edited_data['ad_name']); ?>"  name="ad_name" class="form-control" placeholder="Ad campaign name" type="text">
											
											<?php echo $validation->error_message("ad_name","<span style='color:red'>");
											?>
											
											<!-- 
											$validation->set_val() is having 2 parameter
											1st is a field name and second is for default value or edit mode populated value.//This method used to populate the text field value
											
											$validation->error_message() is having 2 params first is the field name and second is the opening tag of html tag where error should show in designed form,do not clode the tag it will autoclose the opened tag passed over it.
											
											-->
											
										</div>
										<div class="form-group">
											<label>Target url</label>
											<input value="<?php echo $validation->set_val("end_url",$_edited_data['end_url']); ?>"  name="end_url" class="form-control" placeholder="Target Url" type="text">
											
											<?php echo $validation->error_message("end_url","<span style='color:red'>");
											?>
											
										</div>
										<div class="form-group">
											<label>Creative Banner</label>
											<input class="form-control" name="ad_media_file" type="file" >
											
											<?php 
											if(isset($_edited_data['ad_media_file']) && $_edited_data['ad_media_file']!="")
											{
												echo '<img style="max-width:300px;height:auto" src="AD_MEDIA/'.$_edited_data['ad_media_file'].'"   />';
											}
											
											echo $validation->error_message("ad_media_file","<span style='color:red'>");
											?>
										</div>
										<div class="form-group">
											<label>Campaign Type</label>
											
											<select <?php  if(isset($_GET['id']) && $_GET['id']!=""){ echo "disabled"; } ?> name="campaign_type" class="form-control input-md">
													<option <?php echo $validation->set_select("campaign_type","1",$_edited_data['campaign_type']); ?> value="1">CTR (Click basis)</option>
													<option <?php echo $validation->set_select("campaign_type","2",$_edited_data['campaign_type']); ?> value="2">CPM (impression every 1k)</option>
												</select>
												
												<!--
												
												$validation->set_select() is having 3 params for first is field name second is 
												for seting selected=selected if value matched in failed post, and third is for seleted by default in edit mode
												-->
												
										</div>
										 
												
										</div>
										<div class="form-group">
											<label>Ad Campaign Status </label>
											
											<select  name="is_active" class="form-control input-md">
													<option <?php echo $validation->set_select("is_active","1",$_edited_data['is_active']); ?> value="1">Enabled</option>
													<option <?php echo $validation->set_select("is_active","0",$_edited_data['is_active']); ?> value="0">Disabled</option>
												</select>
												
										</div>
										
									</fieldset>
									<div>
										<button type="submit" class="btn btn-primary">
											<i class="fa fa-save"></i>
											Submit
										</button>
									</div>
								</form>
			  				</div>
			  			</div>

Step 3: Create a Table for advertise add/edit using following sql dump

CREATE TABLE IF NOT EXISTS `tbl_ads` (
  `a_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `ad_name` varchar(255) NOT NULL,
  `ad_media_file` text NOT NULL,
  `end_url` tinytext NOT NULL,
  `total_impression` int(11) NOT NULL,
  `campaign_type` enum('1','2') NOT NULL COMMENT '1 for click base 2 for impression',
  `is_active` enum('0','1') NOT NULL DEFAULT '1',
  `approved` enum('0','1') NOT NULL DEFAULT '0',
  `is_delete` enum('0','1') NOT NULL DEFAULT '0',
  `added_date` datetime NOT NULL,
  `updated_date` datetime NOT NULL,
  `remark` text NOT NULL,
  PRIMARY KEY (`a_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Step 4: Now need to post the form and recieve data and show errors, Recieve post Before the HTML form

if(isset($_POST['is_post'])) //check form is posted
{
	extract($_POST);//extract the form in its filed name vars using php function extract
	
	
	//now create a is_unique rule for ad name for AD/EDIT MOde both 
	
	if(isset($edit_id) && $edit_id!=0)//it means it is in edit mode
	{
		$is_unique_expression="tbl_ads::ad_name::a_id!=".$edit_id;
	}
	else
	{
		$is_unique_expression="tbl_ads::ad_name";
	}
	
	/*
	So for -> is_unique_expression :: First data is for `table_name`
	second is for `column_name` to match
	third is for `where_condition` in edit case or any specific requirement (optional)
	ALl are seperated with :: (double colon)
	*/
	 
	
		//validation rules 
		
		$config_validation=array(
		array('field'=>"ad_name",
		"label"=>"Ad Campaign Name",
		"rules"=>"required|is_unique[".$is_unique_expression."]",
		),
		array('field'=>"campaign_type",
		"label"=>"Campaign Type",
		"rules"=>"required",
		),
		array('field'=>"is_active",
		"label"=>"Ad Campaign Status",
		"rules"=>"required",
		),
		array('field'=>"ad_media_file",
		"label"=>"Creative Banner",
		"rules"=>"file_required|valid_file[AD_MEDIA::png,jpg,jpeg,gif]",
		),
		array('field'=>"end_url",
		"label"=>"Target Url",
		"rules"=>"required|valid_url",
		)
		);
		
		//rule names must seperated with pipe |
		/*
		rule      =>    usage
		required  =>  means must required item
		valid_url =>   used for validate a url format
		file_required => user to set must upload validation for a input type file
		valid_file => valid file passes a string for validate file time in []
		              fist is the folder name seperated with double column :: second is 
					  for extnsions seperated with comma (,)
		is_unique => used for matching value already exist in database or not for 
					both  edit and add case, in edit case we can pass the extra where case
					for self safe 
		
		
		*/
	
	
	//now pass the configuration array of fileds
	$validation->init($config_validation);
	
	
	//if form successfully submitted by passing all rules//
	if($validation->form_success==1)
	{
		
		//do whatever want to do
		if(isset($edit_id) && $edit_id!=0) //detect it is in edit mode
		{
			$ad_media_file = (isset($validation->return_array['ad_media_file']))?$validation->return_array['ad_media_file']:"";
			
			//$validation->return_array is a array set the key with file field name if file successfully posted.
			//means it set the file field name key in '$validation->return_array' with input type file name.
			//so we can get the uploaded file name by passing the file type field name in $validation->return_array like this >> $validation->return_array['ad_media_file'];
			
			
			//this is save action when we edit any item
			$date=date('Y-m-d H:i:s');
			
			$update = array(
				'ad_name' => $ad_name,
				'is_active' => $is_active,
				'dimension' => $dimension,
				'end_url' => $end_url,
				'updated_date' => $date
			);
			if($ad_media_file!="")
			{
				$update['ad_media_file'] = $ad_media_file;
			}
			//Add the WHERE clauses
			$where_clause = array(
				'a_id' => $edit_id
			);
			$updated = $database->update( 'tbl_ads', $update, $where_clause, 1 );
			if( $updated )
			{
				header('location:campaign.php?msg=Ad Campaign Updated Successfully!');
			}
		}
		else
		{ //detect that form post done for add a new campaign
			$ad_media_file = $validation->return_array['ad_media_file'];
	
			//this is add action where we add new item
			$date=date('Y-m-d H:i:s');
			$data = array(
				'ad_name' => $ad_name,
				'campaign_type' => $campaign_type,
				'user_id' => $_SESSION['user_id'],
				'is_active' => $is_active,
				'dimension' => $dimension,
				'ad_media_file' => $ad_media_file,
				'end_url' => $end_url,
				'added_date' => $date,
				'updated_date' => $date
				
			);
			
			$add_query = $database->insert( 'tbl_ads', $data );
			if( $add_query )
			{
				header('location:campaign.php?msg=Ad Campaign Added Successfully!');
			}
		}
		//do whatever want to do
	}
	else{
		
		//echo "<pre>";
		//print_r($validation->errors_array);
		//die;
		
		//$validation->errors_array is the complete array with all errors of form.
	}

	
}

Please Comment If any problem in this. I’ll assist you to use this form validation library

Custom form validation in Codeigniter

Hi Geeks,
Today i am sharing you the Custom form validation example in codeigniter. Suppose we have a custom requirement to validate the data with our own custom rules like email already exist in database, So for this type on need can be resolve only with custom callback functions .these are the following steps to create a custom validation for any form.
Step 1: Form Layout form.php in views

<?php echo form_open_multipart('',array('name' => 'registration_form', 'id' => 'registration_form', 'class' => 'form-horizontal')); ?>
                      <div class="item form-group">
                        <label class="control-label col-md-3 col-sm-3 col-xs-12">First Name</label>
                        <div class="col-md-6 col-sm-6 col-xs-12">
                          <input type="text" id="f_name" name="f_name" value="<?php     set_value('f_name'); ?>" class="form-control"  />
                          <span class="required-server"><?php echo form_error('f_name'); ?> </span>
                        </div>
                      </div>
 <div class="item form-group">
                        <label class="control-label col-md-3 col-sm-3 col-xs-12">Last Name</label>
                        <div class="col-md-6 col-sm-6 col-xs-12">
                          <input type="text" id="l_name" name="l_name" value="<?php     set_value('l_name'); ?>" class="form-control"  />
                          <span class="required-server"><?php echo form_error('l_name'); ?> </span>
                        </div>
                      </div>
 <div class="item form-group">
                        <label class="control-label col-md-3 col-sm-3 col-xs-12">Email</label>
                        <div class="col-md-6 col-sm-6 col-xs-12">
                          <input type="text" id="user_email" name="user_email" value="<?php     set_value('user_email'); ?>" class="form-control"  />
                          <span class="required-server"><?php echo form_error('user_email'); ?> </span>
                        </div>
                      </div>
 <div class="item form-group">
                        <label class="control-label col-md-3 col-sm-3 col-xs-12">Password</label>
                        <div class="col-md-6 col-sm-6 col-xs-12">
                          <input type="password" id="user_password" name="user_password" value="<?php     set_value('user_password'); ?>" class="form-control"  />
                          <span class="required-server"><?php echo form_error('user_password'); ?> </span>
                        </div>
                      </div>



 <?php echo form_close(); ?>

Now , We have 4 fields in this form –
first name,last name, email and password
for validate these fields codeigniter already provided rules in form_validation library:
Some of the rules are following listed:
valid_email,required,valid_email,valid_url,min_length[5]|max_length[12] etc.

But Now we need to detect that email already registered in Database ,So we need to create a callback function for validating the email already check in database.

Note:Codeigniter itself providing rule for ‘value already exists in database’ but here our purpose is to demonstrate the custom form validation in codeigniter thats why we are assuming that this need a custom form validation.
Step 2. Create a callback to match the field’s value in database

public function check_email_exists($email){
        
        $where_array = array( user_email' => $email );
        $this->db->where($where_array);
        $switch = $this->db->count_all_results("tbl_user");
        if ($switch != NULL){
            $this->form_validation->set_message('check_email_exists', 'The %s field value already exist, please try another.');
            return false;
        }else{
            return true;
        }
    }

Step 3. Load Form validation library in controller’s Action or Constructor method as following:

$this->load->library('form_validation');

Step 4. Now pass the array of validation rules for the form in add method of user controller as following:

public function add()
{
	$this->load->library('form_validation');

	$config = array(
				array(
					'field' => 'f_nme',
					'label' => 'First Name',
					'rules' => 'trim|required|xss_clean'
				),
				array(
					'field' => 'l_name',
					'label' => 'Last Name',
					'rules' => 'trim|required|xss_clean'
				),
				array(
					'field' => 'user_email',
					'label' => 'Email Address',
					'rules' => 'trim|required|xss_clean|callback_check_email_exists'   //here we have added the callback which we have created by appending callback_ to its method name
				),
				array(
					'field' => 'user_password',
					'label' => 'Password',
					'rules' => 'trim|required|xss_clean'
				)
				 
			);
			
			$this->form_validation->set_rules($config);  //pass the rules array here

					if ($this->form_validation->run() == FALSE) {
						//by default initial load condition
					 $this->load->view('form');
					}
					else{
					//controll comes here if form submitted successfully
					//Now add or update the data //

					$save_data = array(
									'f_name' =>$this->input->post('f_name'),
									'l_name' => $this->input->post('l_name'),
									'user_email=> $this->input->post('user_email'),
									'user_password' => $this->input->post('user_password')
					);

					$this->db->insert('tbl_user',$save_data);//add data to tabke user

				}
}
?>

Please comment here if you have any query regarding to this form validation snippet or not cleared anything.

How to work with AngularJS as frontend and PHP MYSQL as backend

Hi Geeks,

In this tutorial you will learn that how to work with AngularJs as web frontend or in any hybrid app and get retrieve data from database using php and mysql. We have created restful webservice for return records to angular app.

Now steps for making a angularjs app with php and mysql –
Step 1) Create a database and table for fetching content from the table
Note: If you want to use existing database then select you db else create a new db with ‘news_db’ or whatever you want to take a db name.
Now Create a table named ‘news’ for getting data by following sql statement

CREATE TABLE IF NOT EXISTS `news` (
  `id` int(12) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `permalink` varchar(255) NOT NULL,
  `details` text NOT NULL,
  `thumbnail` varchar(255) NOT NULL,
  `category_id` int(12) NOT NULL,
  `source_id` int(12) NOT NULL,
  `datetime` int(12) NOT NULL,
  `day` int(2) NOT NULL,
  `month` int(2) NOT NULL,
  `year` int(4) NOT NULL,
  `hits` int(12) NOT NULL,
  `published` int(1) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

Now Dump some dummy records by following insert statement:

--
-- Dumping data for table `news`
--

INSERT INTO `news` (`id`, `title`, `permalink`, `details`, `thumbnail`, `category_id`, `source_id`, `datetime`, `day`, `month`, `year`, `hits`, `published`) VALUES
(1, 'MY NEWS TITLE 1', '', 'The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 ', '11621455015936.jpg', 1, 0, 1455015936, 9, 2, 2016, 45, 1),
(2, 'MY NEWS TITLE 2', '', 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. ', '76911455015952.jpg', 2, 0, 1455015952, 9, 2, 2016, 73, 0);

Step 2) Create a file named config.php with following code

<?php
$details=array();
$details['server_host']="localhost";//server host name
$details['mysql_name']="root";//your mysql user name
$details['mysql_password']="";//your mysql user name
$details['mysql_database']="news_db";//your database name
?>

change credential according to your database and server host
Step 3) Now create a file for webservices named wsdl.php
Define Cross origin headers in this file by following code

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
?>

Now code for getting data from database and provide in restful json format by following code

<?php
include 'config.php';//make the cofig file include
global $details;//make the connection vars global

if($_GET['method'] == "load_news")
{
	$conn = new mysqli($details['server_host'], $details['mysql_name'],$details['mysql_password'], $details['mysql_database']);	
	$result = $conn->query("SELECT title,details,hits FROM news");
	$data=array();
	while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
		$row=array();
	   $row['title']=addslashes($rs["title"]);
	   $row['details']=addslashes($rs["details"]);
	   $row['hits']=addslashes($rs["hits"]);
	   
	   $data[]=$row;
		
	}
	$jsonData=array();
	$jsonData['records']=$data;

	$conn->close();
	echo json_encode($jsonData);

}
?>

So complete Code for wsdl.php is following

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
include 'config.php';//make the cofig file include
global $details;//make the connection vars global

if($_GET['method'] == "load_news")
{
	$conn = new mysqli($details['server_host'], $details['mysql_name'],$details['mysql_password'], $details['mysql_database']);	
	$result = $conn->query("SELECT title,details,hits FROM news");
	$data=array();
	while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
		$row=array();
	   $row['title']=addslashes($rs["title"]);
	   $row['details']=addslashes($rs["details"]);
	   $row['hits']=addslashes($rs["hits"]);
	   
	   $data[]=$row;
		
	}
	$jsonData=array();
	$jsonData['records']=$data;

	$conn->close();
	echo json_encode($jsonData);

}
?>

Step 4) Now Start with frontend
Step for Getting data from database using angularjs as frontend and php & mysql as backed
make a file named index.html
include the script which i have attached with this post

<script src="js/angular.1.4.8.min.js"></script>

Now make a ng-app with following html

<div ng-app="myApp" ng-controller="newsCtrl"> 

</div>

make a html table format inside the div for getting data from datasource(php/mysql restful service) as following

<div ng-app="myApp" ng-controller="newsCtrl"> 
<table border="2">
  <tr ng-repeat="x in names">
    <td>{{ x.title }}</td>
    <td>{{ x.details }}</td>
    <td>{{ x.hits }}</td>
  </tr>
</table>
</div>

Now put the script that call the restful web service and load data to the table

<script>
var app = angular.module('myApp', []);
app.controller('newsCtrl', function($scope, $http) {
    $http.get("http://localhost/angular/wsdl.php?method=load_news")
    .then(function (response) {$scope.names = response.data.records;});
});
</script>

Now complete Code for index.html

<script src="js/angular.1.4.8.min.js"></script>
<div ng-app="myApp" ng-controller="newsCtrl"> 

<table border="2">
  <tr ng-repeat="x in names">
    <td>{{ x.title }}</td>
    <td>{{ x.details }}</td>
    <td>{{ x.hits }}</td>
  </tr>
</table>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('newsCtrl', function($scope, $http) {
    $http.get("http://localhost/angular/wsdl.php?method=load_news")
    .then(function (response) {$scope.names = response.data.records;});
});
</script>

Congratulations you have completed with this tutorial please provide comments for this tutorial. [viraldownloader id=146 text=’DOWNLOAD COMPLETE CODE’]

Array to Xml Conversion and Xml to Array Convert in PHP

Hi Geeks,
Today i am sharing you a code snippet for converting xml to array with attributes also and vice versa (Convert array to xml). This class is very useful to parse rss feed and to make rss feed in php programming.

In this code snippet we have made a class to convert array XML using php code and also retaining its attibues stored into array . It returns the XML in form of DOMDocument class for further manipulation. This class will throw exception if the tag name or attribute name has illegal characters.

Usage of this class:

 //convert array to xml//
		$php_array = array ();//this is your array data ,it comes from database also or you can define elements in php code also.
	    $root_node="ROOT";//root node of the xml tree like//root , data or anything you want to make super parent tag for the xml
        $xml = Array2XML::createXML($root_node, $php_array);//
        echo $xml->saveXML();
	   
	  //convert  xml to array//
		$xmlstring='';//this varribale will contain xml string
		$xml_data = Array2XML::XML_TO_ARR($xmlstring);//
        

A. Steps for Convert Array to Xml

1.Create a class named Array2XML with following code in file Array2XML.php

<?php

class Array2XML {
 
    private static $xml = null;
	private static $encoding = 'UTF-8';
 
    /**
     * Initialize the root XML node [optional]
     * @param $version
     * @param $encoding
     * @param $format_output
     */
    public static function init($version = '1.0', $encoding = 'UTF-8', $format_output = true) {
        self::$xml = new DomDocument($version, $encoding);
        self::$xml->formatOutput = $format_output;
		self::$encoding = $encoding;
    }
 
    /**
     * Convert an Array to XML
     * @param string $node_name - name of the root node to be converted
     * @param array $arr - aray to be converterd
     * @return DomDocument
     */
    public static function &createXML($node_name, $arr=array()) {
        $xml = self::getXMLRoot();
        $xml->appendChild(self::convert($node_name, $arr));
 
        self::$xml = null;    // clear the xml node in the class for 2nd time use.
        return $xml;
    }
 
    /**
     * Convert an Array to XML
     * @param string $node_name - name of the root node to be converted
     * @param array $arr - aray to be converterd
     * @return DOMNode
     */
    private static function &convert($node_name, $arr=array()) {
 
        //print_arr($node_name);
        $xml = self::getXMLRoot();
        $node = $xml->createElement($node_name);
 
        if(is_array($arr)){
            // get the attributes first.;
            if(isset($arr['@attributes'])) {
                foreach($arr['@attributes'] as $key => $value) {
                    if(!self::isValidTagName($key)) {
                        throw new Exception('[Array2XML] Illegal character in attribute name. attribute: '.$key.' in node: '.$node_name);
                    }
                    $node->setAttribute($key, self::bool2str($value));
                }
                unset($arr['@attributes']); //remove the key from the array once done.
            }
 
            // check if it has a value stored in @value, if yes store the value and return
            // else check if its directly stored as string
            if(isset($arr['@value'])) {
                $node->appendChild($xml->createTextNode(self::bool2str($arr['@value'])));
                unset($arr['@value']);    //remove the key from the array once done.
                //return from recursion, as a note with value cannot have child nodes.
                return $node;
            } else if(isset($arr['@cdata'])) {
                $node->appendChild($xml->createCDATASection(self::bool2str($arr['@cdata'])));
                unset($arr['@cdata']);    //remove the key from the array once done.
                //return from recursion, as a note with cdata cannot have child nodes.
                return $node;
            }
        }
 
        //create subnodes using recursion
        if(is_array($arr)){
            // recurse to get the node for that key
            foreach($arr as $key=>$value){
                if(!self::isValidTagName($key)) {
                    throw new Exception('[Array2XML] Illegal character in tag name. tag: '.$key.' in node: '.$node_name);
                }
                if(is_array($value) && is_numeric(key($value))) {
                    // MORE THAN ONE NODE OF ITS KIND;
                    // if the new array is numeric index, means it is array of nodes of the same kind
                    // it should follow the parent key name
                    foreach($value as $k=>$v){
                        $node->appendChild(self::convert($key, $v));
                    }
                } else {
                    // ONLY ONE NODE OF ITS KIND
                    $node->appendChild(self::convert($key, $value));
                }
                unset($arr[$key]); //remove the key from the array once done.
            }
        }
 
        // after we are done with all the keys in the array (if it is one)
        // we check if it has any text value, if yes, append it.
        if(!is_array($arr)) {
            $node->appendChild($xml->createTextNode(self::bool2str($arr)));
        }
 
        return $node;
    }
 
    /*
     * Get the root XML node, if there isn't one, create it.
     */
    private static function getXMLRoot(){
        if(empty(self::$xml)) {
            self::init();
        }
        return self::$xml;
    }
 
    /*
     * Get string representation of boolean value
     */
    private static function bool2str($v){
        //convert boolean to text value.
        $v = $v === true ? 'true' : $v;
        $v = $v === false ? 'false' : $v;
        return $v;
    }
 
    /*
     * Check if the tag name or attribute name contains illegal characters
     * Ref: http://www.w3.org/TR/xml/#sec-common-syn
     */
    private static function isValidTagName($tag){
        $pattern = '/^[a-z_]+[a-z0-9\:\-\.\_]*[^:]*$/i';
        return preg_match($pattern, $tag, $matches) && $matches[0] == $tag;
    } 
	
	/*
     * Convert xml string into array.
     */
    public static function XML_TO_ARR($xmlstring)
	{
		$xml = simplexml_load_string($xmlstring, "SimpleXMLElement", LIBXML_NOCDATA);
		$json = json_encode($xml);
		$array = json_decode($json,TRUE);
		return $array;
    }
}
?>

2. Now Include the class

<?php

include 'Array2XML.php';//include with path to your class file 'Array2XML'

?>

3. Defining Array or get it from database then call the createXML method for generating xml file

$data_array = array(
    '@attributes' => array(
        'type' => 'fiction'
    ),
    'book' => array(
        array(
            '@attributes' => array(
                'author' => 'Jeetendra Singh'
            ),
            'title' => 'Learning PHP programming',
            'price' => 'Free'
        ),
        array(
            '@attributes' => array(
                'author' => 'Shailesh Verma'
            ),
            'title' => 'Linux Aspects',
            'price' => '$15.61'
        ),
        array(
            '@attributes' => array(
                'author' => 'Eric Basendra'
            ),
            'title' => 'IOS Dev',
            'Company' => 'Oxilo India',
            'price' => array(
                '@attributes' => array(
                    'discount' => '10%'
                ),
                '@value' => '$18.00'
            )
        )
    )
);

Now Call createXML method as following

  $root_node="data";//root node of the xml tree like//root , data or anything you want to make super parent tag for the xml
  $xml = Array2XML::createXML($root_node, $data_array);//
  
  $xml_STR = $xml->saveXML();// put string in xml_STR
  $xml->save('array_to_xml_convert.xml'); // save data in array_to_xml_convert.xml file

B. Steps for Convert Xml to Array

1. Define the xml oe get the xml string into a varribale

$xmlstring='<?xml version="1.0"?>
<x>
  <hello>4</hello>
  <var name="the-name" attr2="something-else">
    <n0>first</n0>
    <n1>second</n1>
    <n5>fifth</n5>
    <sub x="4.356" y="-9.2252">
      <n0>sub1</n0>
      <n1>sub2</n1>
      <n2>sub3</n2>
    </sub>
  </var>
  <foo>1234</foo>
</x>';

Or

$xmlstring=file_get_contents('myxml_file_path.xml');//get the string load into a varriable using 
file_get_contents method of php

2.Now call the XML_TO_ARR function as following

$Array_Data = Array2XML::XML_TO_ARR($xmlstring);//pass the xml string 
print_r($Array_Data);//print your array

[viraldownloader id=138 text=’DOWNLOAD COMPLETE CODE’]

CONVERT HTML TO PDF IN CODEIGNITER Using MPDF

Hi Geeks,
Today I am Sharing you the code for making pdf or download pdf files in codeigniter. In this Code snippet we have used the MPDF Kit for generating pdf of html views or dynamic templates. So Following are the steps to create/convert HTML to PDF In Codeigniter using MPDF

Prerequisites :- GD LIBRARY SHOULD BE ACTIVE ON YOUR WEB SERVER

Step 1: Download the Mpdf  Class and methods from here or  https://www.mediafire.com/?9qmqaw2yqlo5caa
Now extract the zip file and put the mpdf folder to application >> third_party folder (this folder Exists in Application folder in codeigniter app )
Step 2. Now make a ci library to call/communicate the mpdf methods and classes from your ci controllers

Now go to libraries folder in application folder and create a file named : M_pdf.php having following code snippet.

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class m_pdf {
    
    function m_pdf()
    {
        $CI = & get_instance();
        log_message('Debug', 'mPDF class is loaded.');
    }
 
    function load($param=NULL)
    {
        include_once APPPATH.'/third_party/mpdf/mpdf.php';
         
        if ($params == NULL)
        {
            $param = '"en-GB-x","A4","","",10,10,10,10,6,3';          		
        }
         
        //return new mPDF($param);
        return new mPDF();
    }
}

Step 3: Now in any of your controller where you want to use or convert the view to pdf output

You can see the calling of our created libary by loading the libarray using this->load_library, and pass the data whatever you required in your view or get the data from model and just pass to your pdf view and use/render that data in your view just like a normal view and controllers.

for sample , We have created a method named save_download having following code

 

 public function save_download()
  { 
		//load mPDF library
		$this->load->library('m_pdf');
		//load mPDF library


		//now pass the data//
		 $this->data['title']="MY PDF TITLE 1.";
		 $this->data['description']="";
		 $this->data['description']=$this->official_copies;
		 //now pass the data //

		
		$html=$this->load->view('pdf_output',$this->data, true); //load the pdf_output.php by passing our data and get all data in $html varriable.
 	 
		//this the the PDF filename that user will get to download
		$pdfFilePath ="mypdfName-".time()."-download.pdf";

		
		//actually, you can pass mPDF parameter on this load() function
		$pdf = $this->m_pdf->load();
		//generate the PDF!
		$pdf->WriteHTML($html,2);
		//offer it to user via browser download! (The PDF won't be saved on your server HDD)
		$pdf->Output($pdfFilePath, "D");
		 
		 	
  }
  

By using this code you will able to make a functionality to convert html to pdf in codeigniter:
If you face any struggle in this please Comment below – Thanks & Cheers 🙂

Progress bar for php form post , Download the Code

Hi Geeks,
Now php has a feature for tracking the progress of multipart form submit. we can show the progress in percentage for user convenience .you can download the source code if you want to create progress bar in php form.
Following are the steps to create a progress bar for php form post.
Step 1. Add script and css for upload progress functionality working

<!--script & css required for form upload progress code-->
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="upload_script.js"></script>
<script type="text/javascript" src="form.min.js"></script>
<link rel="stylesheet" href="upload_progress.css" />
<!--script required for form upload progress code-->

Step 2. Form Tag should look like

<form id="myform" method="post"  enctype="multipart/form-data" action="upload.php">

Note: form id we have used myform so if you want to change the form id then you need to change in upload_script.js file also

Step 3. Add the placement for showing progress bar

<!--progress bar html code -->
<div id="progress-div"><div id="progress-bar"></div></div>
<div id="targetLayer"></div>
<div id="loader-icon" style="display:none;"><img src="ajax-loader.gif" /></div>
<!--progress bar html code -->

Step  4. In your upload or form post action you can add your code for demo purpose we have use as following:

<?php 
if(isset($_POST['title']))
{
	$title=$_POST['title'];
	$desc=$_POST['desc'];
	
	$filename=uniqid("file_attach_").$_FILES['file_upload']['name'];
	
	move_uploaded_file($_FILES['file_upload']['tmp_name'],"./uploads/".$filename);
	
	$flag=file_exists("./uploads/".$filename);
	
	/* check if file uploaded successfully */
	if($flag){
		/* make your db connection or use existing connected db */
		$con=mysql_connect("localhost","root","");
		mysql_select_db("progress_db");
		/*now insert the details in table */
		$insert_statement="insert into upload_table set `title`='".$title."',`description`='".$desc."',`file_name`='".$filename."' ";
		
		mysql_query($insert_statement);
		
		echo "Form processed Completely";
	}
	else
	{
		echo "Some Error occured";
	}
	
	 
	
	
}
?>

[viraldownloader id=126 text=’Download the Source code by sharing us on facebook.’]

Text to Image Convert using php code . Download source Code

Hi Geeks,
In this tutorial we will learn that how to Create and save dynamic image in php using gd library or Text to Image Convert using php code . in this example we have a requirement to create a image with specific width and height and specific background and watermark also.
So that we have created a PHP Class to generate and save the image to specific folder or path.
please follow the steps to achive this task.
Step 1. Create a class file for generate image with name class.img.php with following code:

<?php
class IMG_PROCESS{

var $_font1="";
var $_font2="";
var $_font_size="";
var $_font_size_watermark="";

public function __construct($font_1,$font_2,$font_size="40",$font_size_watermark="15")
{
	$this->_font1=$font_1;
	$this->_font2=$font_2;
	$this->_font_size=$font_size;
	$this->_font_size_watermark=$font_size_watermark;
	
}

public function imagettftext_cr(&$im, $size, $angle, $x, $y, $color, $fontfile, $text)
{
	// retrieve boundingbox
	$bbox = imagettfbbox($size, $angle, $fontfile, $text);
	// calculate deviation
	$dx = ($bbox[2]-$bbox[0])/2.0 - ($bbox[2]-$bbox[4])/2.0;         // deviation left-right
	$dy = ($bbox[3]-$bbox[1])/2.0 + ($bbox[7]-$bbox[1])/2.0;        // deviation top-bottom
	// new pivotpoint
	$px = $x-$dx;
	$py = $y-$dy;
	return imagettftext($im, $size, $angle, $px, $y, $color, $fontfile, $text);
}

public function generate_img($name,$savepath,$size_arr,$watermark,$rgb=array("34","96","76"))
{
 
     
$image = imagecreate($size_arr['width'],$size_arr['height']);
$rgb_background = imagecolorallocate($image,$rgb[0],$rgb[1],$rgb[2]);
$grey_shade = imagecolorallocate($image,40,40,40);
$white = imagecolorallocate($image,255,255,255);


// Local font files, relative to script
$otherFont = $this->_font1;
$font = $this->_font2;

 
$i=0;
while($i<10){
$this->imagettftext_cr($image,12,$this->_font_size_watermark,rand(100,500),rand(200,500),$grey_shade,$otherFont,$watermark);
$i++;
}

// Main Text

$w=$size_arr['width'] / 2 ;
$h=$size_arr['height'] / 2 ;

$this->imagettftext_cr($image,$this->_font_size,0,$w,$h,$white,$font,$name);
$this->imagettftext_cr($image,$this->_font_size_watermark,0,$w,$h+30,$white,$otherFont,$watermark);
imagejpeg($image,$savepath);

}

}
?>

Step 2. make another php file with any name.
and include the class file as follow:

<?php
include 'class.img.php';//include class file for generate image
?>

Now create a instance of img class with font file names and sizes as following :

<?php
$font_file1="fonts/arial.ttf";
$font_file2="fonts/times.ttf";
$font_size="40";
$font_size_watermark="15";
?>

Init with font files and font sizes as follow:

<?php
$img_obj=new IMG_PROCESS($font_file1,$font_file2,$font_size,$font_size_watermark);
?>

Now generate a single image as follow:

<?php
	$text_to_image="THIS IS MY TEXT";//
	$size_arr=array("width"=>"500","height"=>"500"); //define height and width
	$savepath="images/my_image_test.jpg";
	$watermark="w3school test";
	$rgb=array("0","0","0");//define a black rgb scheme
	$img_obj->generate_img($text_to_image,$savepath,$size_arr,$watermark,$rgb); //call the generate image 
?>

Generate multiple images in loop as following code :

<?php
$text=array("MY IMAGE TEXT 1","MY IMAGE TEXT 2","MY IMAGE TEXT 3","MY IMAGE TEXT 4","MY IMAGE TEXT 5",);
foreach($text as $title)
{
	 
	//
	$img_name=strtolower(str_replace(" ","-",$title));
	$size_arr=array("width"=>"1366","height"=>"768"); //define height and width
	$savepath="images/".$img_name.".jpg";
	$watermark="w3school test watermark";
	$rgb=array("34","96","76");//define a light green rgb scheme
	$img_obj->generate_img($title,$savepath,$size_arr,$watermark,$rgb); //call the generate image function
	// 
 
	
}
?>

Complete Code of above snippets:

<?php 
include 'class.img.php';//include class file for generate image

//now create a instance of img class with font file names and sizes as following 
$font_file1="fonts/arial.ttf";
$font_file2="fonts/times.ttf";

$font_size="40";
$font_size_watermark="15";

$img_obj=new IMG_PROCESS($font_file1,$font_file2,$font_size,$font_size_watermark); //init with font files and font sizes

//now generate a single image  

	$text_to_image="THIS IS MY TEXT";//
	$size_arr=array("width"=>"500","height"=>"500"); //define height and width
	$savepath="images/my_image_test.jpg";
	$watermark="w3school test";
	$rgb=array("0","0","0");//define a black rgb scheme
	$img_obj->generate_img($text_to_image,$savepath,$size_arr,$watermark,$rgb); //call the generate image 


//now generate a single image  

 


//generate multiple images in loop

$text=array("MY IMAGE TEXT 1","MY IMAGE TEXT 2","MY IMAGE TEXT 3","MY IMAGE TEXT 4","MY IMAGE TEXT 5",);
foreach($text as $title)
{
	 
	//
	$img_name=strtolower(str_replace(" ","-",$title));
	$size_arr=array("width"=>"1366","height"=>"768"); //define height and width
	$savepath="images/".$img_name.".jpg";
	$watermark="w3school test watermark";
	$rgb=array("34","96","76");//define a light green rgb scheme
	$img_obj->generate_img($title,$savepath,$size_arr,$watermark,$rgb); //call the generate image function
	// 
 
	
}

//generate multiple images in loop

?>

[viraldownloader id=113 text=’Download the Complete Code by Sharing this post and click on generate button after sharing’]

Note: please confirm GD library on your php server. and create a images folder in project with 755 or 775 or 777 permissions.

 

How to make a news aggregator website

Hi Geeks,
I am Sharing you the code for reading a rss feed using php script.
Following are the Steps to make a news aggregator website using rss reader in php
Step 1: Create a form having Rss Urls in select box as following

<p><b>Choose category :</b>
<form method="post" id="myform"  >
<select required name="rssurl">
<option value="">Select</option>
<option value="http://timesofindia.feedsportal.com/c/33039/f/533916/index.rss">India News</option>
<option value="http://timesofindia.feedsportal.com/c/33039/f/533917/index.rss">World News</option>
<option value="http://timesofindia.feedsportal.com/c/33039/f/533922/index.rss">Science News</option>
</select>
<input type="submit" value="Load" />
</form>
</p>

Step 2. Php code to recieve the submitted post and rss url. and get the rss output in object and parse the feed or rss using the dom document class and accessing the properties as following:

<?php

if(isset($_POST['rssurl']))
{
	echo '<h1>Search Result for rss url:'.$_POST['rssurl'].'</h1>';
	$rssurl=$_POST['rssurl'];
	$rss = new DOMDocument();
	$rss->load($rssurl);
	$feed = array();
	foreach ($rss->getElementsByTagName('item') as $node) {
		$item = array ( 
			'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
			'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
			'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
			'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
			);
		array_push($feed, $item);
	}
	$limit = 5;
	for($x=0;$x<$limit;$x++) {
		$title = str_replace(' & ', ' &amp; ', $feed[$x]['title']);
		$link = $feed[$x]['link'];
		$description = $feed[$x]['desc'];
		$date = date('l F d, Y', strtotime($feed[$x]['date']));
		echo '<p><strong><a href="'.$link.'" title="'.$title.'">'.$title.'</a></strong><br />';
		echo '<small><em>Posted on '.$date.'</em></small></p>';
		echo '<p>'.$description.'</p>';
	}
}
?>

Final Complete Code:

<p><b>Choose category :</b>
<form method="post" id="myform"  >
<select required name="rssurl">
<option value="">Select</option>
<option value="http://timesofindia.feedsportal.com/c/33039/f/533916/index.rss">India News</option>
<option value="http://timesofindia.feedsportal.com/c/33039/f/533917/index.rss">World News</option>
<option value="http://timesofindia.feedsportal.com/c/33039/f/533922/index.rss">Science News</option>
</select>
<input type="submit" value="Load" />
</form>
</p>
<?php

if(isset($_POST['rssurl']))
{
	echo '<h1>Search Result for rss url:'.$_POST['rssurl'].'</h1>';
	$rssurl=$_POST['rssurl'];
	$rss = new DOMDocument();
	$rss->load($rssurl);
	$feed = array();
	foreach ($rss->getElementsByTagName('item') as $node) {
		$item = array ( 
			'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
			'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
			'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
			'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
			);
		array_push($feed, $item);
	}
	$limit = 5;
	for($x=0;$x<$limit;$x++) {
		$title = str_replace(' & ', ' &amp; ', $feed[$x]['title']);
		$link = $feed[$x]['link'];
		$description = $feed[$x]['desc'];
		$date = date('l F d, Y', strtotime($feed[$x]['date']));
		echo '<p><strong><a href="'.$link.'" title="'.$title.'">'.$title.'</a></strong><br />';
		echo '<small><em>Posted on '.$date.'</em></small></p>';
		echo '<p>'.$description.'</p>';
	}
}
?>

Conclusion : Select your category and click on go button and you will see the fetched news from rss feed.

read rss using php script
read rss using php script