There are many xml tutorials for php on the web, but few show how to
parse xml using DOM. I would like to take this opportunity to show
there is an alternative to the widespread SAX implementation for php
DOM (Document Object Model) and SAX (Simple API for XML) have
different philosophies on how to parse xml. The SAX engine is
extremely event-driven. When it comes across a tag, it calls an
appropriate function to handle it. This makes SAX very fast and
efficient. However, it feels like you're trapped
inside an eternal loop when writing code. You find yourself using many global variables
and conditional statements.
On the other hand, the DOM method is somewhat memory intensive. It
loads an entire xml document into memory as a hierarchy. The upside
is that all of the data is available to the programmer organized
much like a family tree. This approach is more intuitive,
easier to use, and affords better readability.
In order to use the DOM functions, you must configure php by specifying
the '--with-dom' argument. They are not a part of the standard
configuration. Here is a sample compilation.
%> ./configure --with-dom --with-apache=../apache_1.3.12
%> make install
How DOM structures XML
Since DOM loads an entire xml string or file into memory as a tree,
this allows us to manipulate the data as a whole. To show what xml
looks like as a tree, take this xml document as an example.