Home > DeveloperSection > Beginner > XML Document Object Model (DOM) in PHP

XML Document Object Model (DOM) in PHP


PHP PHP 
Ratings:
0 Comment(s)
 5092  View(s)
Rate this:

XML Document Object Model (DOM) in PHP

Document Object Model (DOM) provides a standard set of objects for HTML and XML documents, and a standard interface for accessing and manipulating them. Since DOM parser is a tree-based parser so it transforms an XML document into a tree structure.

DOM is separated into different parts (Core, XML, and HTML) and different levels:

·         Core DOM - defines a standard set of objects for any structured document

·         XML DOM - defines a standard set of objects for XML documents

·         HTML DOM - defines a standard set of objects for HTML documents

Let’s have an example how to load and display xml file with the help of DOM in PHP.

Example: Load and Output XML file Using DOM

Below is an XML file.

<?xml version="1.0" encoding="ISO-8859-1"?>

<note>

    <to> Amit </to>

    <from> Arun </from>

    <subject> XML Parser</subject>

    <message> This is testing message on PHP XML parser</message>

</note>

Now save this file with ‘TestXml.xml’ name.

<?php

        // Create instance of DOMDocument 

        $doc =new DOMDocument();

        // Load xml filefrom specified loaction

        $doc->load("TestXml.xml");

        // Display XML file structure

        echo $doc->saveXML();

 

?>

Output:

XML Document Object Model (DOM) in PHP

Example:   Creating XML Document using with DOMDocument

<?php

    //CreatingDOMDocument instance with xml version 1.0

    $doc = new DOMDocument('1.0');

    // Set output format

    $doc->formatOutput = true;

 

    // create root node

    $root = $doc->createElement('book');

    // add root node as child of domdocument

    $root = $doc->appendChild($root);

    // Create child node

    $title = $doc->createElement('title');

    // add child node with root node

    $title = $root->appendChild($title);

    // Assign child node value

    $text = $doc->createTextNode('This is the title');

    $text = $title->appendChild($text);

    //display number of bytes written and wrote file with name tesAt.xml file name at specified location

    echo 'Wrote: ' . $doc->save("tesAt.xml") . ' bytes';

 

?>

Note: save () method is used to save file at specified location.

Output:

XML Document Object Model (DOM) in PHP

Now open, above specified location in save () method.

XML Document Object Model (DOM) in PHP

This is the required ‘tesAt.xml’ file which is creating through the code..


Don't want to miss updates? Please click the below button!

Follow MindStick