#native_company# #native_desc#

DOM XML: An Alternative to Expat Page 4

By Matt Dunford
on December 27, 2000

A Simple Example

Let’s start with a simple example to tie everything together.


# make an example xml document to play with

$xmlstr "<" "?" "xml version="1.0"" "?" ">";

$xmlstr .=




    <position type="contract">Web Guy</position>



# load xml data ($doc becomes an instance of 

# the DomDocument object)

$doc xmldoc($xmlstr);

# get root node "employee"

$employee $doc->root();

# get employee's children ("name","position")

$nodes $employee->children();

# let's play with the "position" node

# so we must iterate through employee's

# children in search of it

while ($node array_shift($nodes))


    if (
$node->name == "position")


$position $node;




# get position's type attribute

$type $position->getattr("type");

# get the text enclosed by the position tag

# shift the first element off of position's children

$text_node array_shift($position->children());

# access the content property of the text node

$text $text_node->content;

# echo out the position and type

echo "position: $text<BR>";

"type: $type";


The example should print out the following:
position: Web Guy
type: contract
The while loop is essential for finding the position node. The
employee node really has five children nodes: three text, one name,
and one position. The text nodes contain the newlines at the end of
the lines. This may seem strange at first, but DOM considers any
string (even those containing only whitespace) as text and makes an
appropriate node for them.
If you want to ensure that the employee node only has two child
nodes, you will have to write the xml entry like this


<employee><name>Matt</name><position type="contract">Web Guy</position></employee>