Re: Handling XML output in a slim way
| From: | Daniel Schierbeck | Date: | Wed, 01 Sep 2004 16:11:29 +0000 |
| Subject: | Re: Handling XML output in a slim way | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-195418@lists.php.net to get a copy of this message | ||
Markus Fischer wrote:
Hi, up until now, when outputing XML I've been constructing the output as a continous string-soup in such ways like [...] $xml .= printf('<item name="%s">%s</item>', makeXmlSave($name), makexmlSave($contentOfItem)); [...] makeXmlSave() makes sure that quotes, ampersand, < and > are properly escaped with their entity reference. However I was thinking if it wasn't possible to e.g. generated a a complete DOM tree first and then just having this tree being dumped as XML. I'm using PHP4 right now. thanks, - Markus In PHP5 the simplexml functions make it very easy to read/edit XML documents. For instancefriends.xml: <friends> <friend> <name>Charlotte</name> <age>21</age> </friend> <friend> <name>Dan</name> <age>25</age> </friend> <friend> <name>Jennifer</name> <age>19</age> </friend> </friends> With simplexml you can load that XML document into an object: <?php $friends = simplexml_load_file('friends.xml'); foreach ($friends->friend as $friend) { echo "Name: {$friend->name}; Age: {$friend->age}\n"; } ?> Which would output: Name: Charlotte; Age: 21 Name: Dan; Age: 25 Name: Jennifer; Age: 19 You can also edit the object and save it, either as an XML file or as an XML-formatted string. Search for 'simplexml' on php.net to see the full documentation. But it only works in PHP5 ;) -- Daniel Schierbeck