Friday, April 27, 2007

Simple XML Parsing with PHP 4

Here's a very simple way to parse a small XML file with PHP 4 using the DOMXML module. This approach only makes sense since the file I'm working with is very small.
$qsOption = "";

// Make sure the file exists.
if ( !$dom = domxml_open_file("C:\path\to\file\file.xml") ) {
//echo "Error while parsing the document\n";
//exit;
// We'll exit quietly instead.
}
else
{
$root = $dom->document_element();
$nodes = $dom->get_elements_by_tagname("topic");
$element = new DomElement();
foreach($nodes as $node)
{
$element = $node;
$qsOption = $qsOption . "<option value=\"" .
$element->get_attribute("tid") . "\">" .
$element->get_content() . "</option>";
}
}

No comments: