DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Kalatravas has posted 29 posts at DZone. View Full User Profile

PHP Script That Returns Records From A Mysql Database In XML Format

  • submit to reddit
        // description of your code here



// This script just defines the MySQL constants.

DEFINE ('DB_USER', 'root');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'kostas_123');

// No closing PHP tag to avoid 'headers already sent' errors.


// getEmployees.php

// This script returns all of the employees as XML.
// This script may only return the employees in a given department, if a departmentId value is passed in $_GET.

// Send the content-type header:
header('Content-Type: text/xml');

// Start the XML:
echo '<?xml version="1.0" encoding="utf-8" ?>

// Include the database information script:

// Connect to the database:
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

// If a connection was established, run the query:
if ($dbc) { 

	// Define the query:
	$q = 'SELECT employees.*, AS departmentName FROM employees, departments WHERE employees.departmentId =';

	// Add another conditional if the departmentId was passed to this script:
	if (isset($_GET['departmentId']) && ( ((int)$_GET['departmentId']) > 0 ) ) {
		$q .= ' AND employees.departmentId = ' . (int) $_GET['departmentId'];

	// Run the query:
	$r = mysqli_query($dbc, $q);
	// Confirm that some rows were returned:
	if (mysqli_num_rows($r) > 0) {
		// Fetch every row and print it as XML:
		while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
			      echo "<employee>
		} // End of WHILE loop.

	} // End of mysqli_num_rows() IF.

} // End of $dbc IF.

// Complete the XML:
echo '</employees>';