Sunday, September 13 2020

How to Read and Write XML using PHP

In this tutorial explains about How to Read and Write XML using PHP. XML stands for extensible Markup Language. XML is a markup language like HTML. XML was designed to store and transport data.

How to Read and Write XML using PHP

What is XML

XML is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable formats.

Syntax

The syntax rules are simple and easy to use.

XML document must have root element. see the below example

<?xml version="1.0" encoding="UTF-8"?>
<Employees>
<title>Employees</title>
<totalRows>1</totalRows>
<rows>
<record>
<id>1</id>
<name>Emp 1</name>
<team_name>Technical</team_name>
</record>
</Employees>
  1. All elements must have a close tag
  2. XML tags are case sensitive.
  3. In the above example the first line is an optional. If it is exists and it must come first in the document.
  4. There are 5 pre-defined entity reference in XML. These are <, >, &, ‘, ” entities.
  5. Comments syntax is <!– This is a comment –>

How to Read a XML in PHP

  1. file_get_contents – Read entire file into string
  2. simplexml_load_string – Convert xml string into an object
  3. json_encode – Convert into json
  4. json_decode – Convert into associative array

Let’s see the complete code for reading a XML file in PHP

function readXML($fileName, $title) {
        $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'];
            foreach ($results['rows']['record'] as $data) {
                 $newArr['record'][$data['id']] = $data;
            }
        }
         return $newArr;
        
    }

In test.php file, call the above function with parameters.

$result = readXML('Employees.xml', 'Employees');

Then $result returns the array of employees list.

Generate XML

Step 1: Create the XML document

$xmlDoc = new DOMDocument();

Step 2: Create an element and append child elements

$root = $xmlDoc->appendChild($xmlDoc->createElement($title));
$root->appendChild($xmlDoc->createElement("title",$title));

Step 3: Make the output is pretty

$xmlDoc->formatOutput = true;

Step 4: Save the XML file

$xmlDoc->save("Employees.xml");

Let’s see the complete code for Generate a XML file

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($file_name);
        
        //return xml file name
        return $file_name;
    }

In generate.xml file, call the above function with sample data set

$data['title'] = "Employees";
$data['record'] = array(
	array(
		'id' => '1',
		'name' => 'Emp 1',
		'team_name' => 'Technical',	
	),
	array(
		'id' => '2',
		'name' => 'Emp 2',
		'team_name' => 'Technical',	
	)
);

generateXML($data);

See the Employees.xml file output in the below

Generate xml file using php

How to Integrate PHP CRUD Operations using XML

Share Your Thoughts

phpexpertise

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