[PHP] How to read an XML using DOM

By | 09th Mar 2014 | 2 min read

If you are a PHP programmer or a Web programmer you would eventually encounter a situation where you need to process XML. Since XML (Xtensible Markup Language) is a widely using format for exchange of information there are libraries to parse an XML file in PHP. Read on to know how to read an XML using DOM.

The easiest way to read a well-formed XML file is to use the Document Object Model (DOM) library. In this section we are going to create an object and then load the well-formed XML file. Below is an example of well-formed XML (sports.xml).

        <manager>Alex Ferguson</manager>
        <team>Manchester united</title>
        <manager>George Morrell</manager>

The code to read the books XML file and to display only the author's name using the DOM is given below

      $doc = new DOMDocument();
      $doc->load( 'sports.xml' );
      $sports = $doc->getElementsByTagName( "football" );
      foreach ( $sports as $football )  {
        $managers = $football->getElementsByTagName( "manager" );
        $manager = $authors->item(0)->nodeValue;
        echo "$manager\n";

We will create a new DOMdocument object and load the sports XML into that object using the load method. We can get a list of all of the elements with the given name using the getElementsByName method.

Within the loop of the football nodes, the script uses the getElementsByName method to get the nodeValue for the manager tags. The nodeValue is the text within the node.

You can run the PHP script and below is the output:

      Alex Ferguson