XML SimpleXML

SimpleXML is an easy way of getting an element's attributes and text, if you know the XML document's layout. It’s new in PHP 5. Compared to DOM or the Expat parser, SimpleXML just takes a few lines of code to read text data from an element.
There are 4 Ways to get an instance of SimpleXMLElement:
  1. simplexml_load_file – Load an XML document from a file. You may also access a remote file (HTTP for example).
  2. simplexml_load_string – Load and XML string. Please keep in mind the XML needs to be well-formed.
  3. SimpleXMLElement - Directly instantiate the SimpleXMLElement class. This requires a parameter starting the XML document. If you directly instantiate this class, you are typically using SimpleXML for XML output.
  4. simplexml_import_dom – Returns and instance of SimpleXMLElement from a DOM object. You can bring over that advanced object and make life simple!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
 
$xml = simplexml_load_file("test.xml");
 
echo $xml->getName() . "<br />";
 
foreach($xml->children() as $child)
 
  {
 
  echo $child->getName() . ": " . $child . "<br />";
 
  }
 
?>
The output of the code above will be:
-- Note --

To: Tove

From: Jani

Heading: Reminder

Message: Don't forget me this weekend!