PHP SimpleXML

Posted by midhun pottmmal On Friday, 28 December 2012 0 comments

SimpleXML is new in PHP 5. It is an easy way of getting an element's attributes and text, if you know the XML document's layout.
Compared to DOM or the Expat parser, SimpleXML just takes a few lines of code to read text data from an element.
SimpleXML converts the XML document into an object, like this:

                                                            
  • Elements - Are converted to single attributes of the SimpleXMLElement object. When there's more than one element on one level, they're placed inside an array
  • Attributes - Are accessed using associative arrays, where an index corresponds to the attribute name
  • Element Data - Text data from elements are converted to strings. If an element has more than one text node, they will be arranged in the order they are found
SimpleXML is fast and easy to use when performing basic tasks like:
  • Reading XML files
  • Extracting data from XML strings
  • Editing text nodes or attributes

XML file


<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

Example

<?php
$xml = simplexml_load_file("test.xml");

echo $xml->getName() . "<br>";

foreach($xml->children() as $child)
  {
  echo $child->getName() . ": " . $child . "<br>";
  }
?>

Output

1
2
3
4
5
note
to: Tove
from: Jani
heading: Reminder
body: Don't forget me this weekend!

0 comments:

Post a Comment

Fashion