Home >Backend Development >PHP Tutorial >How can I create an XML object from scratch using SimpleXML in PHP?
Creating XML Objects from Scratch with SimpleXML
SimpleXML, a PHP library, offers comprehensive functionality for manipulating XML documents. One query often arises: is it possible to establish an XML object completely from scratch?
Initially, it appears that SimpleXML exclusively allows importing existing XML strings, barring direct creation of XML objects from scratch. However, upon closer examination, the function simplexml_load_string() provides a solution.
By supplying the desired root string to simplexml_load_string(), you can create an XML object. Although this approach may seem like a workaround due to the need to initially hardcode XML into a string, it remains a viable solution.
Alternatively, DOMDocument functions can also accomplish XML object creation. However, the naming conventions may evoke confusion, as the term "DOM" suggests document manipulation rather than XML creation.
Example: Creating an XML Object from Scratch
The following code sample demonstrates how to create an XML object from scratch using simplexml_load_string():
<code class="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();</code>
This code generates the following XML output:
<code class="xml"><?xml version="1.0"?> <news newsPagePrefix="value goes here"> <content type="latest"/> </news></code>
The above is the detailed content of How can I create an XML object from scratch using SimpleXML in PHP?. For more information, please follow other related articles on the PHP Chinese website!