While PHP's SimpleXML functions are often used to manipulate existing XML strings, they can also be utilized to create XML objects from scratch.
Creating a New XML Object
To generate a new XML object, employ the simplexml_load_string() function:
<code class="php">$newsXML = new SimpleXMLElement("<news></news>");</code>
This creates a blank
<code class="php">$newsXML->addAttribute('newsPagePrefix', 'example'); $newsIntro = $newsXML->addChild('content'); $newsIntro->addAttribute('type', 'latest'); // Output the XML Header('Content-type: text/xml'); echo $newsXML->asXML();</code>
This will produce the following XML:
<code class="xml"><?xml version="1.0"?> <news newsPagePrefix="example"> <content type="latest"/> </news></code>
By utilizing SimpleXML in this way, programmers can effortlessly create and modify XML documents without having to resort to DOMDocument, despite its somewhat confusing name.
The above is the detailed content of How can SimpleXML be used to programmatically create XML objects in PHP?. For more information, please follow other related articles on the PHP Chinese website!