Parsing XML in PHP

PHP offers several methods for parsing XML files. This example uses the built-in DOM functionality for PHP5.

Suppose we have an XML file which holds a collection of robots. Transformers to be more specific.

<?xml version="1.0" encoding="utf-8"?>
<robots>
  <robot id="1">
    <name>Optimus Prime</name>
    <race>Autobots</race>
  </robot>
  <robot id="2">
    <name>Megatron</name>
    <race>Decepticons</race>
  </robot>
</robots>

The following snippet parses the XML file and outputs the results.

<?php

  $xmlDocument = new DOMDocument();
  $xmlDocument->load('transformers.xml');

  // Get all elements with the robot tag
  $robots = $xmlDocument->getElementsByTagName('robot');

  foreach($robots as $robot){
    // Get the id attribute of the robot
    $robotId = $robot->getAttribute('id');

    // Get the value of the name tag
    $robotName = $robot->getElementsByTagName('name')->item(0)->nodeValue;

    // Get the value of the race tag
    $robotRace = $robot->getElementsByTagName('race')->item(0)->nodeValue;

    print "Id: ".$robotId."\n".
            "Name: ".$robotName."\n".
            "Race: ".$robotRace."\n";

  }

?>

Output:

Id: 1
Name: Optimus Prime
Race: Autobots
Id: 2
Name: Megatron
Race: Decepticons
This entry was posted in PHP and tagged , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?