PHP SimpleXML
PHP SimpleXML handles the most common XML tasks and leaves the rest for other extensions.
The SimpleXML extension provides is a simple way of getting an XML element's name and text.
SimpleXML converts the XML document (or XML string) 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 are placed inside an array
- Attributes are accessed using associative arrays, where an index corresponds to the attribute name
- Text inside elements is 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 tasks like:
- Reading/Extracting data from XML files/strings
- Editing text nodes or attributes
Assume we have the following TEXT IN XML file, "note.xml":
<?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>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Output keys and elements of the $xml variable
(which is a SimpleXMLElement object):
<?php
$xml=simplexml_load_file("note.xml");
print_r($xml);
?>
THE OUTPUT FOR THE CODE ABOVE$xml=simplexml_load_file("note.xml");
print_r($xml);
?>
SimpleXMLElement Object ( [to] => Tove [from] => Jani [heading] => Reminder [body] => Don't forget me this weekend! )
Output the data from each element in the XML file:
<?php
$xml=simplexml_load_file("note.xml");
echo $xml->to . "<br>";
echo $xml->from . "<br>";
echo $xml->heading . "<br>";
echo $xml->body;
?>
The above code outputs the following:
ToveJani
Reminder
Don't forget me this weekend!
<?php
$xml=simplexml_load_file("note.xml");
echo $xml->getName() . "<br>";
foreach($xml->children() as $child)
{
echo $child->getName() . ": " . $child . "<br>";
}
?>
The code above outputs the following:
to: Tove
from: Jani
heading: Reminder
body: Don't forget me this weekend!
PHP __construct() Function
The __construct() function creates a new SimpleXMLElement object.
No comments:
Post a Comment