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

09.25.2010
| 2960 views |
  • submit to reddit
        // description of your code here


<?php

// mysql.inc.php

// This script just defines the MySQL constants.

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

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


<?php 

// 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" ?>
<employees>
';

// Include the database information script:
require_once('mysql.inc.php');

// 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.*, departments.name AS departmentName FROM employees, departments WHERE employees.departmentId = departments.id';

	// 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>
			<id>{$row['id']}</id>
			<firstName>{$row['firstName']}</firstName>
			<lastName>{$row['lastName']}</lastName>
			<email>{$row['email']}</email>
			<phoneExt>{$row['phoneExt']}</phoneExt>
			<hireDate>{$row['hireDate']}</hireDate>
			<departmentName>{$row['departmentName']}</departmentName>
	</employee>
	";
		} // End of WHILE loop.

	} // End of mysqli_num_rows() IF.

} // End of $dbc IF.

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

?>