Is it possible to use PHP's SimpleXML functions to create an XML object from scratch? Looking through the function list, there's ways to import an existing XML string into an object that you can then manipulate, but if I just want to generate an XML object programmatically from scratch, what's the best way to do that?
I figured out that you can use simplexml_load_string() and pass in the root string that you want, and then you've got an object you can manipulate by adding children... although this seems like kind of a hack, since I have to actually hardcode some XML into the string before it can be loaded.
I've done it using the DOMDocument functions, although it's a little confusing because I'm not sure what the DOM has to do with creating a pure XML document... so maybe it's just badly named :-)
SimpleXML is an extension that allows us to easily manipulate and get XML data. SimpleXML provides an easy way of getting an element's name, attributes and textual content if you know the XML document's structure or layout.
Start with $videos = simplexml_load_file('videos. xml'); You can modify video object as described in SimpleXMLElement documentation, and then write it back to XML file using file_put_contents('videos. xml', $videos->asXML()); Don't worry, SimpleXMLElement is in each PHP by default.
Sure you can. Eg.
<?php $newsXML = new SimpleXMLElement("<news></news>"); $newsXML->addAttribute('newsPagePrefix', 'value goes here'); $newsIntro = $newsXML->addChild('content'); $newsIntro->addAttribute('type', 'latest'); Header('Content-type: text/xml'); echo $newsXML->asXML(); ?>
Output
<?xml version="1.0"?> <news newsPagePrefix="value goes here"> <content type="latest"/> </news>
Have fun.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With