Home > Article > Backend Development > How can you programmatically create XML objects using SimpleXML?
Creating XML Objects from Scratch with SimpleXML
Is it possible to generate XML objects from scratch using SimpleXML functions? The provided function list suggests methods for importing existing XML strings into objects, but how can we programmatically create XML objects?
Use SimpleXML with Root String
You can use simplexml_load_string() with a root string to create an object. However, this approach requires hardcoding some XML into a string before loading it, which may seem like a workaround.
DOMDocument Functions
An alternative is to utilize DOMDocument functions. However, the involvement of the DOM in creating pure XML documents can be confusing.
Creating XML Objects from Scratch with SimpleXML
Creating XML objects from scratch with SimpleXML is straightforward:
Example:
<code class="php">$newsXML = new SimpleXMLElement("<news></news>"); $newsXML->addAttribute('newsPagePrefix', 'value goes here'); $newsIntro = $newsXML->addChild('content'); $newsIntro->addAttribute('type', 'latest'); echo $newsXML->asXML();</code>
Output:
<code class="xml"><?xml version="1.0"?> <news newsPagePrefix="value goes here"> <content type="latest"/> </news></code>
This approach allows you to programmatically create complex XML objects with ease.
The above is the detailed content of How can you programmatically create XML objects using SimpleXML?. For more information, please follow other related articles on the PHP Chinese website!