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 prednisone injection with bactrim. more specific.

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

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


  $xmlDocument = new DOMDocument();

  // 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";




Id: 1
Name: Optimus Prime
Race: Autobots
Id: 2
Name: Megatron
Race: Decepticons

This entry was posted in PHP. 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?

  • Advertisement

  • Categories