logo

PHP DomDocument Tutorial

Add comment

This will be a quick tutorial that will show you how to use PHP’s DOMDocument to parse your XML so you do not have to use XML parser. In this tutorial you’ll see how to loop through your XML file and how to extract some specific data. For this, we will use XML file that is available on w3school.com.

Load DocumentTop

First thing we have to do is to make an instance of DOMDocument class.

$dom = new DOMDocument();

Now that we have instance, we can load document. To do that we’ll use load method. As an argument we pass path to our XML file.

$dom->load('http://www.w3schools.com/XML/simple.xml');

Now our document is loaded and we can do with it what we want.

Loop Through XMLTop

Now we will loop through our XML file. Let’s say we want to print data from food elements. To do that we have to select them first. We’ll do that by using getElementsByTagName method and pass name of our element (food).

$food = $dom->getElementsByTagName('food');

If you do var_dump on $food variable you’ll see that you get instance of DOMNodeList class. It has method item and variable $length so you can loop through them or use foreach to do the job. When you loop you’ll get each element that you got from your query as DOMElement and then you can do new queries or modify that element. We’ll just loop.

<ul>
< ?php
//Loop through each item
foreach ($food as $elem) {
?>
    <li>
        <table>
            <tbody>
                <tr>
                    <td><b>Name:</b></td>
                    <td>< ?php echo $elem->getElementsByTagName('name')
                                        ->item(0)
                                        ->nodeValue; ?></td>
                </tr>
                <tr>
                    <td><b>Description:</b></td>
                    <td>< ?php echo $elem->getElementsByTagName('description')
                                        ->item(0)
                                        ->nodeValue; ?></td>
                </tr>
                <tr>
                    <td><b>Price:</b></td>
                    <td>< ?php echo $elem->getElementsByTagName('price')
                                        ->item(0)
                                        ->nodeValue; ?></td>
                </tr>
                <tr>
                    <td><b>Calories:</b></td>
                    <td>< ?php echo $elem->getElementsByTagName('calories')
                                        ->item(0)
                                        ->nodeValue; ?></td>
                </tr>
            </tbody>
        </table>
    </li>
< ?php
}
?>
</ul>

As you can see, we do new queries on our element retrieved from loop. We want element with tag names name, description, price and calories. When we get our element we want first of them that is in list of elements retrieved from query and it’s value. This is how we loop through our XML. Result should be something like this.

  • Name: Belgian Waffles
    Description: two of our famous Belgian Waffles with plenty of real maple syrup
    Price: $5.95
    Calories: 650
  • Name: Strawberry Belgian Waffles
    Description: light Belgian waffles covered with strawberries and whipped cream
    Price: $7.95
    Calories: 900
  • Name: Berry-Berry Belgian Waffles
    Description: light Belgian waffles covered with an assortment of fresh berries and whipped cream
    Price: $8.95
    Calories: 900
  • Name: French Toast
    Description: thick slices made from our homemade sourdough bread
    Price: $4.50
    Calories: 600
  • Name: Homestyle Breakfast
    Description: two eggs, bacon or sausage, toast, and our ever-popular hash browns
    Price: $6.95
    Calories: 950

Retrieve Specific ElementTop

Let’s say we want to get value of name element in third food element and print it out. We will use something like this.

$third = $dom->getElementsByTagName('food')
             ->item(2);
echo sprintf(
    'Name of third element is: <b>%s</b>',
    $third->getElementsByTagName('name')
          ->item(0)
          ->nodeValue
);

You should get result like this.

Name of third element is: Berry-Berry Belgian Waffles

ConclusionTop

DOM classes in PHP are very powerful and I like to use them for parsing XML much more then XML parser because they are build in object-oriented way and can be very easy extended. Thank you for reading.

Related Posts
  • 21.05.2010 -- Multi-Language Site (6)
    It's been a while since I last posted something because I was very busy. So let's do something usefu...
  • 07.04.2010 -- Edit XML (15)
    I had an idea about creating tutorial that will cover manipulating XML in PHP. The idea was to creat...
  • 02.09.2009 -- PHP Walker Class (1)
    In this tutorial we will create walker class. This class will load results by executing given SQL qu...
  • 27.07.2010 -- Upload Images With MySQL (0)
    [tinytoc level="1"]Intro[/tinytoc] Ok, let's continue with tutorial requests. This tutorial will ...
  • 02.01.2010 -- Enable E-mail In PHP – Win (0)
    This will be a quick tutorial that will show you how to enable e-mail function in PHP on Windows....
  • 09.09.2009 -- AJAX Multi-Level Comments (41)
    In this tutorial we will create multi level comments. You must have seen comments on youtube and tha...
  • 18.08.2009 -- Permissions Using Bitwise (3)
    This will be a quick tutorial on how to use bitwise operators in PHP to create permissions control. ...

logo

15 comments to “PHP DomDocument Tutorial”

  1. @buzzknow
    Not here on my site but I can do one (although if you check Edit XML you could get some idea).

    @parvez
    I’ve answered to you question here.

  2. parvez says:

    Sir,
    thnx 4 this useful tutorial.
    i hv a quesry..how we delete a specific node
    from xml file.
    example:

    1
    mhtkkk

    2
    mhtkkk

    i want delete id=2 hole node.

  3. buzzknow says:

    any tuts how to create XML with this class?

    thanks

  4. It seams that WP removed XML (if you placed any) so could you place encoded it.

  5. Runtest says:

    This was a life saver. I do have a question though, what if you have a sub element like

    And you want to get each of those topppings?

  6. Rajendra Mandawar says:

    Add Specific Element in xml object $dom and save in XML file.

    load(‘http://www.w3schools.com/XML/simple.xml’);
    $food = ‘food’;
    $child = ‘quantity’; // New Element
    $qty=’500′; // New Element value
    $foodList = $dom->getElementsByTagName(‘food’);
    $foodCnt = $foodList->length;

    for ($idx = 0; $idx getElementsByTagName($food)->item($idx)->appendChild($dom->createElement($child));
    $childNode->appendChild($dom->createTextNode($qty));
    $qty = $qty + $idx;
    }

    $dom->formatOutput = true;// set the formatOutput attribute of domDocument to true
    // save XML as string or file
    $test1 = $dom->saveXML(); // put string in test1
    $dom->save(‘sample.xml’);
    ?>

    Hope it helps someone.

  7. [...] Now we’ll load each child element of item so we can manipulate with them. If you don’t know how to load them, check my previous tutorial about XML here. [...]

  8. Faisal says:

    Thank you, This makes my life easier to implement a feature in my site.
    I agree that the DOM classes are much more easy to use.

    Thanks for the info

  9. Nice wrapper :) . I’m having plans on creating new tutorial about using DOMDocument as database for some store software but right now don’t have time. I may use it. Thanks.

  10. I’ve created a wrapper around DOMDocument called SmartDOMDocument to overcome some of its shortcomings.

    You can find here: http://beerpla.net/projects/smartdomdocument

    Hope it helps someone.

  11. shlomy says:

    great tutorial , finaly i got it.

    thanks

  12. rohith says:

    it is helpful for guys like me who was looking for a kick start about domdocument xml parsing.

  13. Ok, will do tutorial soon about that, but I have one tutorial pending now so when that one is done, I’ll do your :) .

  14. Sham Sehgal says:

    Hi, nice tutorial. I have a query, can u post some info on manipulating xml file data with php. I want to edit xml file data with php form, I searched internet a lot, but not able to figure out exact thing, may be I am losing something.

    Thanks in advance.

  15. Aziz Light says:

    Nice tutorial, thanks a lot, that was helpful.

Leave a Reply


 *


 *


logo
logo
Powered by Wordpress | Designed by Elegant Themes | CopyRight ©2010 php4every1.com