simple xml api

From: Date: Thu, 30 Jan 2003 17:18:24 +0000
Subject: simple xml api
Groups: php.xml.dev 
Request: Send a blank email to php-xml-dev+get-6@lists.php.net to get a copy of this message
Sam Ruby sent me the following URL: http://dev2dev.bea.com/articlesnews/discussion/thread.jsp?thread=JSchneider_XML It looks really neat, and much in the PHP way of doing things. Take the following XML document, and I'll show you how easy parsing it is with the Simple API proposed above (ported slightly to PHP). Let's say we're a bar, and we have a list in XML of the different beers on tap. <beers> <beer> <name>Becks</name> <nation>Germany</nation> </beer> <beer> <name>Heineken</name> <nation>Netherlands</nation> </beer> <beer> <name>Hefeweißer</name> <nation>Germany</name> </beer> <beer> <name>Samuel Adams</name> <nation>USA</nation> </beer> <beer> <name>Coors</name> <nation>Not surprisingly, no one claims ownership</nation> </beer> <beer> <name>Budweiser</name> <nation>Germany</name> </beer> </beers> <?php // $file contains the xml above $tap = new Simple_XML($file); foreach ($tap->beers as $beer) { var_dump($beer->name); // string "Name of Beer" } $nations = array_unique($tap->range($tap->beers, "nation")); // All the represented nations in the file $germanBeers = $tap->search($tap->beers, create_function('if ($beer->nation == "Germany") return 1; return 0;') ); // you can also query using Xpath documents var_dump($tap->beers[0]->name); // string (5) "Becks" // Modifying documents $tap->beers[0]->name = "Killians Red"; $tap->beers[0]->nation = "Ireland"; // Add a meta data element, and set the various data foreach ($tap->beers as $beer) { $beer->metadata->type = "Heavy"; $beer->metadata->audience = "People with chest hair"; // $distributors is another XML document that we now // merge with the current document $beer->metadata->distributors = $distributors->list; $tasty = $beer->name == "Coors" ? "No!" : "Yes"; $beer->metadata->attributes = <<<ASSIGN_XML <attribute> <tasty>$tasty</tasty> </attribute> <attribute> <filling>yes</filling> </attribute> ASSIGN_XML; } ?> To me, this just seems like the PHP5 way of doing XML. Simple, Elegant and Efficient. We could of course provide DOM and SAX for the purists (SAX is also better for large files), and people using XSLT. However, I think this API just maps itself to the problem domain perfectly (and could easily be implemented on top of libxml). Thoughts? -Sterling PS: Yes, I do know xml_parse_into_struct(). This is different. -- "First they ignore you, then they laugh at you, then they fight you, then you win." - Gandhi

« previous php.xml.dev (#6) next »