Posts Tagged PHP

Convert XML to Array using DOM extension in PHP5

The xml2array class convert the XML stored in a string into an ARRAY. We are using the DOM extension of PHP5. The DOM extension replaced the DOM XML extension available in PHP4. The DOM XML extension is depreciated in PHP5.

<?php
class xml2array {
 
	function xml2array($xml) {
		if (is_string($xml)) {
			$this->dom = new DOMDocument;
			$this->dom->loadXml($xml);
		}
 
		return FALSE;
	}
 
	function _process($node) { 
		$occurance = array();
 
		foreach($node->childNodes as $child) {
			$occurance[$child->nodeName]++;
		}
 
		if($node->nodeType == XML_TEXT_NODE) { 
			$result = html_entity_decode(htmlentities($node->nodeValue, ENT_COMPAT, 'UTF-8'), 
                                     ENT_COMPAT,'ISO-8859-15');
		} 
		else {
			if($node->hasChildNodes()){
				$children = $node->childNodes;
 
				for($i=0; $i<$children->length; $i++) {
					$child = $children->item($i);
 
					if($child->nodeName != '#text') {
						if($occurance[$child->nodeName] > 1) {
							$result[$child->nodeName][] = $this->_process($child);
						}
						else {
							$result[$child->nodeName] = $this->_process($child);
						}
					}
					else if ($child->nodeName == '#text') {
						$text = $this->_process($child);
 
						if (trim($text) != '') {
							$result[$child->nodeName] = $this->_process($child);
						}
					}
				}
			} 
 
			if($node->hasAttributes()) { 
				$attributes = $node->attributes;
 
				if(!is_null($attributes)) {
					foreach ($attributes as $key => $attr) {
						$result["@".$attr->name] = $attr->value;
					}
				}
			}
		}
 
		return $result;
	}
 
	function getResult() {
		return $this->_process($this->dom);
	}
}
?>

We can use this class like this.

<?php
	$obj = new xml2array($XML_string);
	$XML_array = $obj->getResult();
?>

, ,

No Comments


Create Drupal form using theme_table() like module list form (Part II)

This post is the second part of Create Drupal form using theme_table() like module list form post. In first part I have showed how we can create Drupal form like we have in Module list pages. In this post, I am showing how we disable some of the checkboxes so user can’t select them like we have for core modules in module list page. We can’t enable/disable core modules in module list.

Drupal Form using theme_table() function (Part II)

Drupal Form using theme_table() function (Part II)

Here I am just showing the changes which we require in code of Part I post.

 $form['featured'] = array(
    '#type' => 'checkboxes',
    '#options' => $options,
    '#default_value' => $status,
);
 
// Change this to 
 
$form['featured'] = array(
    '#type' => 'checkboxes',
    '#options' => $options,
    '#default_value' => $status,
    '#process' => array(
        'expand_checkboxes',
        'featured_disable',
        ),
    '#disabled_products' => $disabled,
);

In above code “$disabled” is an array containing the productid’s of all the products which we want to show as checked and in disable state. The structure of “$disabled” array is similar to “$status” array. We stored this array in “#disabled_products”. We also added “#process” in above code.

“expand_checkboxes” and “featured_disable” are function names which Drupal call when create and render these checkboxes. “expand_checkboxes()” is defined in Drupal core files and we don’t need to define it again.

function featured_disable($form, $edit) {
  	foreach ($form['#disabled_products'] as $key) {
  		$form[$key]['#attributes']['disabled'] = 'disabled';
  	}
 
  	return $form;
}

“featured_disable()” function is very important here. Drupal call this function when renders these checkboxes. Here we assigned “disabled” attribute to each checkbox which we want as disable.

, ,

4 Comments


How know recipient read the email or newsletter?

Sometimes we send the newsletters or emails to lot of peoples and we want to know how many of them read it. Normally the websites like Gmail, Yahoo, Hotmail don’t provide any facility for this purpose. But we can know that by sending HTML emails.

HTML Emails – HTML emails are emails which can contain HTML tags in email body. Like <table>, <tr>, <td>, etc.

The main thing here is we need to send some information to our server when user open the email. So for this, we can place an image in email body and when user open this email the browser send request to our webserver for this image. We can also achieve this by adding javascript code or hidden iframe but normally email clients don’t support javascript code and iframes in email body and they strips out this unwanted code form email body. So, the best way to achieve this is by using images.

<?php
/*send_newsletter.php*/
 
$newsletterid = 25;
 
// array of recipients
$recipients = array('test1@yahoo.com', 'test2@yahoo.com', 'test3@yahoo.com', 'test4@gmail.com', 'test5@gmail.com', 
	'test6@hotmail.com', 'test7@hotmail.com', 'test8@aol.com', 'test9@aol.com', 'test10@yahoo.com');
 
// subject
$subject = 'Newsletter for April';
 
// message
$message = "
<html>
<head>
  <title>Newsletter for April</title>
</head>
<body>
  <p>This is a Demo Newsletter. This is a Demo Newsletter. This is a Demo Newsletter. This is a Demo Newsletter. 
  This is a Demo Newsletter. This is a Demo Newsletter. This is a Demo Newsletter. This is a Demo Newsletter. 
  This is a Demo Newsletter. This is a Demo Newsletter. This is a Demo Newsletter. This is a Demo Newsletter. </p>
  <img src='http://www.akchauhan.com/newsletter_read.php?newsletterid={$newsletterid}' height='1' width='1' /><br/><br/>
  Thanks,<br/>
  www.akchauhan.com
</body>
</html>";
 
// To send HTML mail, the Content-type header must be set
$headers  = 'MIME-Version: 1.0' . "rn";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn";
$headers .= 'From: AKChauhan Blog <anil@akchauhan.com>' . "rn";
 
foreach($recipients as $to) {
	// Mail it
	mail($to, $subject, $message, $headers);
}
?>


I have used a variable $newsletterid to track newsletter. We can also send some extra information in query string as per our requirement.
Like

http://www.akchauhan.com/newsletter_read.php?newsletterid=$newsletterid&userid=$userid


Note: Here I have used mail() function only to make demonstration simple. mail() function is not suitable for sending large number of email in loop. Better we use PEAR::Mail or PEAR::Mail_Queue packages for sending large number of email.

<?php
/*newsletter_read.php*/
 
$newsletterid = $_GET['newsletterid'];
/*Write some code to update your read counter in your database. Or, do whatever you want to 
do when user open your newsletter.*/
mysql_query('UPDATE info SET newsletter_count = newsletter_count + 1 WHERE newsletterid = ' . $newsletterid);
 
// We'll be outputting a JPEG
header('Content-Type: image/jpeg');
 
$im = @imagecreatefromjpeg('images/one_pixel_small_white_image.jpg');
 
imagejpeg($img);
imagedestroy($img);
?>


In above code, first we updated our newsletter read counter in database. We can do other things also like send an email to admin etc. as per requirement. Then we set the Content-Type to image/jpeg as we are going to send a jpeg image. So, we need to tell the browser about the content type of our response. Then, we created a 1 pixel white image usng GD library and outputted it to browser using imagejpeg() function.

, , ,

1 Comment


Assign attributes to options using FormAPI in Drupal

Drupal FAPI does not support this feature but we can add attributes to options by slightly modifying form.inc file.

You only need to change following line in form.inc file.

<?php
        $options .= '<option value="'. check_plain($key) .'"'. $selected .'>'. 
				check_plain($choice) .'</option>';
	//line no. 1437 of form_select_options() in drupal 6.10
?>

with this

<?php
	$options .= '<option value="'. check_plain($key) .'"'. $selected . 
			drupal_attributes($element['#options_attribute'][$key]) . '>'. 
			check_plain($choice) .'</option>';
?>

You can use like it.

<?php
    $shipping_methods = array('1' => 'Standard Two-Day ($17.00 Total Shipping Price)',
        '2' => 'Priority Overnight ($26.00 Total Shipping Price)',
        '3' => 'FedEx Next Day Delivery $23.95',
        '4' => 'FedEx Next Day Delivery $23.95');
 
    $shipping_method_options = array(
        '1' => array('price' => '17.00', 'class' => 'one'),
        '2' => array('price' => '26.00', 'class' => 'two'),
        '3' => array('price' => '23.95', 'class' => 'three'),
        '4' => array('price' => '23.95', 'class' => 'four'));
 
    $form['default_shipping_method'] = array(
        '#title' => t('Shipping Method'),
        '#type' => 'select',
        '#options' => $shipping_methods,
        '#options_attribute' => $shipping_method_options,
        '#default_value' => variable_get('default_shipping_method', 0),
        '#description' => t('You can change your shipping method from here.'),
    );
?>

, ,

1 Comment


Create Drupal form using theme_table() like module list form

I am showing here an example for Drupal form like you saw in Module list pages.

Drupal Form using theme_table() function

Drupal Form using theme_table() function

I am considering here an example of Featured Product Management form so we can easily understand it.

Step 1:- Create a menu hook for registering your page path. This registered path will display the featured product management page.

<?php
function product_menu() {
	$items = array();
	$items['featured_product_mgmt'] = array(
		‘title’ => ‘Manage featured product’,
		‘page callback’ => ‘drupal_get_form’,
		‘page arguments’ => array(’featured_product_form’),
		‘access arguments’ => array(’access product’),
		‘type’ => MENU_CALLBACK,
	);
    return $items;
}
?>

Step 2:- Create form object for your form. Here the important part is “featured” form element of type “checkboxes”. Checkboxes type is a group of checkbox and format a set of checkboxes. #options is an associative array, where the key is the #return_value of the checkbox and the value is displayed. We will store other information like name, category, discount etc. of product in form array so we can display it later.

<?php
function featured_product_form() {
	$query = “SELECT p.*, UNIX_TIMESTAMP(p.create_date) AS create_date, c.name FROM {product} p LEFT JOIN {category} c ON p.cid = c.cid
	WHERE p.status = 1 ORDER BY p.product_name”;
	$rs = db_query($query);
 
	$featured_products = featured_product();
	$status = array();
 
	if ($rs) {
		while ($data = db_fetch_object($rs)) {
            $options[$data->productid] =;
 
            $form[$data->productid]['name'] = array(#value’ => stripslashes($data->product_name));
            $form[$data->productid]['category'] = array(#value’ => stripslashes($data->name));
            $form[$data->productid]['discount'] = array(#value’ => $data->discount . ‘%’);
            $form[$data->productid]['createdon'] = array(#value’ => date(’m-d-Y’, $data->create_date));
    
            if (in_array($data->productid, $featured_products)) {
                $status[] = $data->productid;
            }
		}
	}
 
	$form['featured'] = array(#type’ => ‘checkboxes’,
#options’ => $options,
#default_value’ => $status,
	);
 
	$form['submit'] = array(#type’ => ’submit’,
#value’ => t(’Submit’),
	);
 
	$form['cancel'] = array(#type’ => ‘markup’,
#value’ => l(t(’Cancel’), ‘dashboard’),
	);
 
	$form['#redirect'] = ‘featured_product_mgmt’;
 
	return $form;
}
?>

Step 3:- Create a form submit function. Any form submitted using the “submit” button will pass to their corresponding function if it is available. We will extract the user input from the form array and update our database accordingly.

<?php
function featured_product_form_submit($form_id, $form) {
	$form_values = $form['values'];
	$featured = $form_values['featured'];
 
	$selected_products = array();
 
	foreach($featured as $key => $value) {
		if ($value) {
			$selected_products[] =($value);
		}
	}
 
	$value_string = @implode(,', $selected_products);
 
	// Delete all previous featured products
	$query = “DELETE FROM {product_featured}”;
	db_query($query);
 
	// Insert new featured products
	if (count($selected_products)) {
		$query = “INSERT INTO {product_featured}(productid) VALUES $value_string”;
		db_query($query);
	}
 
	drupal_set_message(t(’Featured product list has been updated successfully.’));
}
?>

Step 4:- Register your modules theme implementation using “hook_theme()” function.

<?php
function product_theme() {
	return array(
		‘featured_product_form’ => array(‘arguments’ => array(’form’ => NULL),),
	);
}
?>

Step 5:- Then finally define your theme function which actually format your form layout in list using the $form array. Using “foreach” loop we navigate through each item of $form array and create $rows array which we pass to “theme_table()” function later. Create the header of your table and call “table_theme()” function with $header and $rows parameters. Call the “drupal_render()” function for render the submit and cancel buttons.

<?php
function theme_featured_product_form($form) {
	$rows = array();
	foreach (element_children($form) as $key) {
		$row = array();
		if (isset($form[$key]['name'])) {
 
			$status = drupal_render($form['featured'][$key]);
			$row[] = array(’data’ => $status,class=> ‘checkbox’);
 
			$row[] = ‘‘. drupal_render($form[$key]['name']) .’‘;
			$row[] = array(’data’ => drupal_render($form[$key]['category']));
			$row[] = array(’data’ => drupal_render($form[$key]['discount']));
			$row[] = array(’data’ => drupal_render($form[$key]['createdon']));
 
			$rows[] = $row;
		}
	}
 
	// Individual table headers.
	$header = array();
	$header[] = array(’data’ => t(’Featured’),class=> ‘checkbox’);
	$header[] = t(’Name’);
	$header[] = t(’Category’);
	$header[] = t(’Discount’);
	$header[] = t(’Created on’);
 
	$output = theme(’table’, $header, $rows);
	$output .= drupal_render($form);
	return $output;
}
?>

, ,

22 Comments