W3Mentor’s guide to simpleXML : Part 3 – Accessing XML Elements
The document element is the object returned when a document is first loaded into SimpleXML. The element name can be used as properties of SimpleXMLElement object to access the element in the tree.i.e if there is a child under the root, we can access it as $se->child, where $se is the document element.
Example code:
1 2 3 4 5 6 7 8 | <?php $xml = "<root><child><subchild>childcontent</subchild></child></root>"; $xmldata = new SimpleXMLElement($xml); /* Access the child element of the root element */ $childinfo = $xmldata->child; /* Access the sub child element from the childinfo element */ $subchildinfo = $childinfo->subchild; ?> |
Sample input xml file – contactfile.xml:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?xml version="1.0"?> <contact id="43956"> <personal> <name> <first>J</first> <middle>J</middle> <last>J</last> </name> <title>Manager</title> <employer>National</employer> <dob>1971-12-22</dob> </personal> </contact> |
Example code:
1 2 3 4 5 6 7 8 | <?php $contact =simplexml_load_file("contactfile.xml"); /* Access the child element of the root element */ $personalinfo = $contact->personal; /* Access the title child element from the personalinfo element */ $title = $personalinfo->title; ?> |
In the example above, accessing a child element is as simple as returning the object from the parent object by using the name of the child element.
