WebReference.com - Part 3 of Chapter 10 from Professional PHP4 XML, from Wrox Press Ltd (4/7) | WebReference

WebReference.com - Part 3 of Chapter 10 from Professional PHP4 XML, from Wrox Press Ltd (4/7)

To page 1To page 2To page 3current pageTo page 5To page 6To page 7
[previous] [next]

Professional PHP4 XML, Chapter 10: Putting It Together

Using DOM To Query an XML Document

Using DOM to query an XML document is rather weird. Once we parse the document we obtain the DOM tree. Then we'll have to parse the tree to perform the query, and we don't have any useful querying feature in the DOM objects that may lead to such a strategy. We won't say that we can't use DOM to query a document, but we'll say that such a solution is uncommon.

If we do decide to use DOM for our query we can use the following code:

<?php
function GetContent($domnode) 
{
    $content = '';
    foreach ($domnode->child_nodes() as $child) {
        if ($child->node_type() == XML_TEXT_NODE) {
            $content .= $child->content;
        }
    }
    return $content;
}
//$doc = xmldocfile("cars.xml");
$doc = domxml_open_file("cars.xml");  
$root = $doc->document_element();
foreach ($root->child_nodes() as $element) {
    if ($element->node_type() == XML_ELEMENT_NODE and 
                                 $element->tagname() == "car") {
        $cond1 = false;
        $cond2 = false;
        foreach ($element->child_nodes() as $car_element) {
            if ($car_element->node_type() == XML_ELEMENT_NODE and 
                                        $car_element->tagname() == "type") {
                if (($type = getContent($car_element)) == "F1") {
                    $cond1 = true;
                }
            }
            if ($car_element->node_type() == XML_ELEMENT_NODE and 
                                    $car_element->tagname() == "maxspeed") {
                if (($maxspeed = getContent($car_element))>300) {
                    $cond2 = true;
                }
            }
            if ($car_element->node_type() == XML_ELEMENT_NODE and 
                                       $car_element->tagname() == "brand") {
                $brand = getContent($car_element);
            }
            if ($car_element->node_type() == XML_ELEMENT_NODE and 
                                       $car_element->tagname() == "model") {
                $model = getContent($car_element);
            }
        }
        if ($cond1 && $cond2) {
            print ("Brand: $brand Model:$model<br />");
        }
    }
}
?>

The code shows a typical approach to using DOM for querying. Traversing the DOM tree and finding the nodes that match some conditions is not that simple, and it isn't short either.


To page 1To page 2To page 3current pageTo page 5To page 6To page 7
[previous] [next]

Created: August 26, 2002
Revised: August 26, 2002

URL: http://webreference.com/programming/php/php4xml/chap10/3/4.html