W3Mentor’s guide to simpleXML : Part 4 – Accessing XML Content

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. The content is then accessed from the childnode object.

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
9
10
11
12
13
14
15
16
17
18
19
20
21
<?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;
$name = $personalinfo->name;
 
/* Object examined with var_dump */
var_dump($title);
 
/* Using print with element containing text-only content */
print "Title: ".$title."\n";
 
/* Object examined with var_dump */
var_dump($name);
 
/* Using print with element containing child elements */
print "Personal name: ".$name."\n";
?>

Generated output for vardump title:
Manager

Generated output for vardump name:

object(SimpleXMLElement)#6 (3) {
["first"]=>
string(1) "J"
["middle"]=>
string(1) "J"
["last"]=>
string(1) "J"
}

In the example above, a vardump of name element denotes the persence of children under it. Accessing a child element is as simple as returning the object from the parent object by using the name of the child element. SimpleXMLElement objects having child elements return a concatenation of all immediate child text nodes but not the content of any child elements.

Share Article/Example:
  • Facebook
  • Twitter
  • del.icio.us
  • Digg
  • DotNetKicks
  • DZone