Sunday, September 20 2020

PHP CRUD Operations using XML

In this tutorial explains about PHP CRUD Operations using XML. CRUD operations contains create, read, update and delete events. CRUD is means for Create, Read, Update, and Delete. Generally CRUD operations are basic data manipulation for database. Here we’ll create a simple PHP application to perform all these operations on a XML not database.

XML Read and Write in PHP

What is XML

XML stands for extensible Markup Language. XML is a markup language like HTML. XML was designed to store and transport data. Read about XML file read and write operation using PHP

PHP CRUD with XML

Create following files in your root directory for template integration

  1. env.php – This file contains all environment variables for access easily in anywhere on the application. It is included in header.php file
  2. header.php
  3. footer.php

In env.php file with following contents

<?php
define('SITE_URL', 'http://localhost/itask/php');
define('CSS_FILE_PATH', SITE_URL . '/webroot/css');
define('JS_FILE_PATH', SITE_URL . '/webroot/js');
define('XML_FILE_PATH', 'webroot/xml');
define('EMPLOYEES_XML_FILE_NAME', 'Employees.xml');
define('EMPLOYEES_XML_FILE_TITLE', 'Employees');
?>

In header.php file with following contents

<?php
include('env.php');
include('Class/Xml.php');
$filename = basename($_SERVER['REQUEST_URI'], '?' . $_SERVER['QUERY_STRING']);
?>
<!doctype html>
<html>
    <head>
        <title>PHP CRUD Operations using XML</title>
        <link rel="stylesheet" href="<?php echo CSS_FILE_PATH;?>/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
        <script src="<?php echo JS_FILE_PATH; ?>/jquery-3.5.1.min.js" crossorigin="anonymous"></script>
        <script src="<?php echo JS_FILE_PATH; ?>/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
    </head>
    <body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary mb-3">
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse">
            <a class="navbar-brand" href="index.php">Home</a>
            <ul class="navbar-nav mr-auto mt-2 mt-lg-0">
                <li class="nav-item <?php echo ($filename == 'manage_employees.php') ? 'active' : ''; ?>">
                    <a class="nav-link" href="index.php">Employees</a>
                </li>
            </ul>
        </div>
    </nav>    

In footer.php file with following contents

</body>
</html>

Then create the following files in the root directory for CRUD

  1. add_employee.php
  2. index.php
  3. Class/Xml.php – It is a library file for XML read and write operations.

In add_employee.php file with following contents

<?php
include('header.php');
$xml = new Xml();

$action = isset($_GET['action']) ? $_GET['action'] : 'Add';
$id = isset($_GET['id']) ? $_GET['id'] : '';
if ($action == "edit") {
    $result = $xml->readXML(EMPLOYEES_XML_FILE_NAME, EMPLOYEES_XML_FILE_TITLE, $id);
}
if ($action == "delete") {
    $result = $xml->readXML(EMPLOYEES_XML_FILE_NAME, EMPLOYEES_XML_FILE_TITLE);
    // remove array element
    unset($result['record'][$id]);

    //This function create a xml object with element root.
    $xml->generateXML($result);

    header('Location: index.php');
}

if (isset($_POST)) {
    $hidden_id = isset($_POST['hidden_id']) ? $_POST['hidden_id'] : '';
    $emp_name = isset($_POST['name']) ? $_POST['name'] : '';
    $team_name = isset($_POST['team_name']) ? $_POST['team_name'] : '';

    if ($emp_name) {
        
        $data = $xml->readXML(EMPLOYEES_XML_FILE_NAME, EMPLOYEES_XML_FILE_TITLE);
        // echo "<pre>";
        // print_r($data);

        // Add a new record
        if (!$hidden_id) {
            $count = 0;
            if ($data['record']) {
                $count = count($data['record']);
            }

            $newArr = $record = array();
            $id = 1 + $count;
            $data['record'][$id]['id'] = $id;
            $data['record'][$id]['name'] = $emp_name;
            $data['record'][$id]['team_name'] = $team_name;
        } else {
            // Update existing record
            $data['record'][$hidden_id]['id'] = $hidden_id;
            $data['record'][$hidden_id]['name'] = $emp_name;
            $data['record'][$hidden_id]['team_name'] = $team_name;
        }
        
        // append child record
        $newArr['title'] = $data['title'];
        $newArr['record'] = $data['record'];

        // print_r($newArr);
        // die;

        //This function create a xml object with element root.
        $xml->generateXML($newArr);

        header('Location: index.php');
        
    }
}

?>
<div class="container">
    <div class="row">
        <div class="col-12 col-sm-12 col-md-12 col-lg-12">
            <div class="mb-2 p-2">
                <a href="manage_employees.php">« Back to Manage Employees </a>
            </div>
            <div class="card bg-light mb-1">
                <div class="col-12 col-sm-12 col-md-12 col-lg-12 kn">
                    <div class="card-body mt-2 p-2">
                        <div id="success_msg"></div>
                        <h2 class="text-primary"><?php echo ucfirst($action); ?> Employee</h2>
                        <form method="POST" action="add_employee.php" name="EmployeeForm" onSubmit="return validateForm(this);">
                        <input type="hidden" name="hidden_id" value="<?php echo isset($result['id']) ? $result['id'] : ''; ?>">
                        <div class="form-group">
                            <label for="name">Name</label>
                            <input type="text" class="form-control" name="name" id="name" placeholder="Enter Employee Name" autocomplete="off" value="<?php echo isset($result['name']) ? $result['name'] : ''; ?>">
                            <span id="name_err" class="text-danger"></span>
                        </div>
                        <div class="form-group">
                            <label for="from_date">Team Name</label>
<input type="text" class="form-control" name="team_name" id="team_name" placeholder="Enter Team Name" autocomplete="off" value="<?php echo isset($result['team_name']) ? $result['team_name'] : ''; ?>">
                            <span id="team_id_err" class="text-danger"></span>
                        </div>
                        <button type="submit" class="btn btn-success">Save</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>       
    </div>
</div>
<script type="text/javascript">
function validateForm()
{ 
    $(".text-danger").html('');
    var error = true;
    var errorInput;
    var name = document.forms["EmployeeForm"]["name"];
    var team_name = document.forms["EmployeeForm"]["team_name"];
    if (name.value == "")                                  
    { 
        $("#name_err").html('Please enter your name.');
        errorInput = name;
        error= false; 
    }
    if (team_name.value == "")    
    { 
        $("#team_id_err").html('Please choose your team.');
        errorInput = team_name; 
        error= false; 
    }
    if (!error) {
        errorInput.focus();
    }
    return error;
}
</script>
<?php include('footer.php');?>

In index.php file with following contents

<?php
include('header.php');
$xml = new Xml();
$data = $xml->readXML(EMPLOYEES_XML_FILE_NAME, EMPLOYEES_XML_FILE_TITLE);
?>
<div class="container">
    <div class="row">
        <div class="col-12 col-sm-12 col-md-12 col-lg-12">
            <div class="card bg-light mb-1">
                <div class="col-12 col-sm-12 col-md-12 col-lg-12 kn">
                    <div class="card-body mt-2 p-2">
                        <div class="float-right">
                            <a href="add_employee.php" class="btn btn-success btn-sm">Add</a>
                        </div>
                        <div id="success_msg"></div>
                        <h2 class="text-primary">Manage Employees</h2>
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th><strong>Nos</strong></th>
                                    <th><strong>Employee Name</strong></th>
                                    <th><strong>Team</strong></th>
                                    <th><strong>Action</strong></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                if ($data['record']) {
                                    foreach ($data['record'] as $k => $result) {
                                ?>
                                <tr>
                                    <td><?php echo $result['id']; ?></td>
                                    <td><?php echo $result['name']; ?></td>
                                    <td><?php echo $result['team_name'] ?></td>
                                    <td>
                                        <a class="btn btn-sm btn-success"
                                        href="add_employee.php?action=edit&id=<?php echo $result['id']; ?>">
                                        Edit
                                        </a>
                                        <a class="btn btn-sm btn-danger" 
                                        href="add_employee.php?action=delete&id=<?php echo $result['id']; ?>" onclick="return confirmDelete();">
                                        Delete
                                        </a>
                                    </td>
                                </tr>
                                <?php
                                    }
                                } else {
                                    echo "<tr><td colspan=5>No Record Found</td></tr>";
                                }
                                ?>
                            <tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>       
    </div>
</div>
<script>
function confirmDelete() {
    if (confirm('Are you sure you want to delete this record')) {
        return true;
    } else {
        return false;
    }
}
</script>
<?php include('footer.php');?>

In Class/Xml.php file with following contents

<?php 
class Xml
{

    function readXML($fileName, $title, $id=NULL) {
        $xml_file_name = XML_FILE_PATH.'/' . $fileName;

        $newArr = array(
            'title' => $title,
            'record' => array()
        );

        if (file_exists($xml_file_name)) {
            // Read entire file into string 
            $xmlfile = file_get_contents($xml_file_name); 
            
            // Convert xml string into an object 
            $new = simplexml_load_string($xmlfile); 
            
            // Convert into json 
            $con = json_encode($new); 
            
            // Convert into associative array 
            $results = json_decode($con, true); 

            $newArr['title'] = $results['title'];

            $recordArr = $results['rows']['record'];

            if (isset($recordArr[0]) && $results) {
                foreach ($results['rows']['record'] as $data) {
                    $newArr['record'][$data['id']] = $data;
                }
            } else {
                $newArr['record'][$results['rows']['record']['id']] = $results['rows']['record'];
            }
        }

        if ($id) {
            return $newArr['record'][$id];
        } else {
            return $newArr;
        }
        
    }
    
    function generateXML($data) {
        $title = $data['title'];
        $rowCount = count($data['record']);
        
        //create the xml document
        $xmlDoc = new DOMDocument();
        
        $root = $xmlDoc->appendChild($xmlDoc->createElement($title));
        $root->appendChild($xmlDoc->createElement("title",$title));
        $root->appendChild($xmlDoc->createElement("totalRows",$rowCount));
        $tabResults = $root->appendChild($xmlDoc->createElement('rows'));
        
        foreach($data['record'] as $result){
            if(!empty($result)){
                $tabResult = $tabResults->appendChild($xmlDoc->createElement('record'));
                foreach($result as $key => $val){
                    $tabResult->appendChild($xmlDoc->createElement($key, $val));
                }
            }
        }
        
        header("Content-Type: text/plain");
        
        //make the output pretty
        $xmlDoc->formatOutput = true;
        
        //save xml file
        $file_name = str_replace(' ', '_', $title).'.xml';
        $xmlDoc->save(XML_FILE_PATH.'/'.$file_name);
        
        //return xml file name
        return $file_name;
    }
}
?>

Finally, the index.php file looks like at the below in the screenshot

manage-employees-in-php-crud-using-xml

Get full source code on Github Here

Share Your Thoughts

phpexpertise

I’m Blogger and Programming Blog, Tutorials, PHP, MySQL, jQuery, Laravel, Wordpress and Codeigniter