20.6 Searching XML


You want to query your XML files and return records.

Technique

Here is a case where xml_parse_into_struct() really does come in handy:

 sites.xml: <sites>     <site>         <title>PHP.net</title>         <url>http://www.php.net/</url>         <description>             The homepage of PHP.         </description>         <keywords>             MySQL, PHP, Documentation, downloads, articles, books         </keywords>     </site> </sites> search.php: <?php $parser = xml_parser_create (); $data = implode ("", file ("sites.xml")); xml_parse_into_struct ($parser, $data, &$d_ar, &$i_ar); xml_parser_free ($parser); $y = 0; foreach ($d_ar as $element) {     $x = 0;     switch (($tag = strtolower($element[tag]))) {         case "title":         case "description":         case "url":             $tmp[$x][$tag] = trim($element[value]);             if (preg_match("/$query/i", trim($element[value]))                  isset($matches[$y])) {                 $matches[$y] = $tmp[$x];             }             break;         case "keywords":             if (preg_match("/$query/i", trim($element[value])) {                 $matches[$y] = $tmp[$x];                 $y++;             }             $x++;             break;     } } ?> 

Comments

After we load the XML document into an array (as described in recipe 20.3) by using the xml_parse_into_struct() function, the rest is extremely simple. Loop through the document, loading each entry into a temporary array, $tmp . We then check whether the document matches our search criteria. If so, we add the item into the $matches array; otherwise , we move on to the next entry.

There are many ways to accomplish a goal, and the preceding approach is just one of those ways. I find it easier to load everything into an array and then display that array, but it is a little slower than the parsing the document in chunks . It is a matter of preference.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net