Over a million developers have joined DZone.

Watch Your POST: Save PHP POST Data as XML

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

One of my main goals when creating PHP web forms is to keep them secure and protected from spammers and automated bots. With the amount of spam that Akismet catches every day, I don't need to be reminded of the importance of securing forms. Since 90+% of my forms are POST transmissions, I've taken a lot of time to develop POST debugging and listening code.

One function I use to keep track of POST submissions is my custom print_r_xml() function. The function takes a given array (in my case, $_POST), cycles through each key, and places each key=>value into XML format. From there, I can save the XML to a file or place the XML into a database.

The function can be used on any array ($_SESSION and $_GET would be good options too!).

The PHP Code

/* print the contents of a url */
function print_r_xml($arr,$wrapper = 'data',$cycle = 1)
	//useful vars
	$new_line = "n";

	//start building content
	if($cycle == 1) { $output = '<?xml version="1.0" encoding="UTF-8">'.$new_line; }
	$output.= tabify($cycle - 1).'<'.$wrapper.'>'.$new_line;
	foreach($arr as $key => $val)
			$output.= tabify($cycle).'<'.htmlspecialchars($key).'>'.$val.'</'.htmlspecialchars($key).'>'.$new_line;
			$output.= print_r_xml($val,$key,$cycle + 1).$new_line;
	$output.= tabify($cycle - 1).'</'.$wrapper.'>';

	//return the value
	return $output;

/* tabify */
function tabify($num_tabs)
	for($x = 1; $x <= $num_tabs; $x++) { $return.= "t"; }
	return $return;

Notice that this function is used recursively when a value is an array.

The Usage

/* test */
$_POST = array(
				'title'=>'Web Developer',
echo print_r_xml($_POST);

The Result

<?xml version="1.0" encoding="UTF-8">
	<title>Web Developer</title>

This function has been a huge help in debugging GET and POST data. Try it out, let me know what you think!

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


Published at DZone with permission of David Walsh. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}