In PHP, simplexml_import_dom() takes a DOMDocument or DOMElement and gives you a SimpleXMLElement for the same XML.
Use it when you already have a DOM tree, for example after loading XML with DOMDocument, and you prefer the shorter SimpleXML syntax such as $xml->title. The two objects share the same XML tree, so a change made through one of them is visible through the other.
Syntax
Call simplexml_import_dom() with the values you need. Start with this line.
PHP
$xml = simplexml_import_dom($dom);
Call
What it does
simplexml_import_dom($dom)
Imports a whole DOMDocument and returns its root element as a SimpleXMLElement.
simplexml_import_dom($dom->documentElement)
Imports one DOMElement. The result is the same as importing the document.
simplexml_import_dom($node, 'MyXmlElement')
Returns an object of your own class, which must extend SimpleXMLElement.
The function needs both the dom and simplexml extensions, and they are enabled in most PHP installs. The opposite direction is dom_import_simplexml(), which turns a SimpleXMLElement into a DOMElement. Nothing is copied in either direction.
getElementsByTagName('item')->item(1) selects the second item element, which is Book.
simplexml_import_dom($node) returns a SimpleXMLElement for that single element.
Printing it shows the element name and its text.
Importing the whole document gives access to the root, and count($shop->item) counts both item elements.
Frequently Asked Questions
It converts a DOMDocument or DOMElement into a SimpleXMLElement so you can use the simple $xml->name syntax on an XML tree that was built or loaded with DOM.
No. The SimpleXMLElement and the DOM object share the same tree, so a change through one is visible through the other.
Use dom_import_simplexml(). It takes a SimpleXMLElement and returns a DOMElement that points to the same node.
Both work. If you pass a DOMDocument, PHP uses its root element. If you pass a DOMElement, that element becomes the root of the SimpleXMLElement.
Use it when part of your code already works with DOMDocument but you want easier reading of values. If you start with plain XML text and only need to read it, simplexml_load_string() is simpler.