PHP: Manipulating and Reading XML with SimpleXML
By:
Jordan
1 month ago
:
Comments (0)
In Programming
SimpleXML is an extension to PHP added in version 5 that turns an XML document into an object making it easy for you to iterate through. The extension solves many of the complexities surrounding XML parsing with PHP prior to version five. The new XML object can be processed with normal property selectors and array itterators making XML simple, hence the name SimpleXML. In this tutorial I'll try to guide you through using this library in PHP.
Creating the Object
Lets start by creating the SimpleXML object. You can create it by loading from a string or loading from a file.
Loading from String:
Alternatively you can pass a string to the constructor of the class (example blow using the XML String from above):
Loading from a File:
Again, there are two ways to create the object from a file and again one involves a function and the other uses the OOP constructor. Lets take a look at the function first. Loading a file using simplexml_load_file() is easy, you only need to pass the XML file path to the function:
Using the Constructor:
Using the construction to load an XML document is fast and efficient:
Notice the two extra arguments in the objects constructor? The 2nd object (NULL) allows you to specify additional parameters but isn't needed (they tell the object how to parse the XML data). The 3rd object, true, is very important in this example. It tells the constructor that the first argument ("myXMLDocument.xml") is a file rather than a string.
The Object - Simple XML Reading
The SimpleXMLElement object is an array of SimpleXMLElement objects. You use them as such. To access elements, you only need to supply the tag name:
Notice the root movies is used in the path above? This is because $xml beings with movies. It is Movies.
Access the Second Object where there are multiple items
Use the object just as you would an array when there are multiple occurrences of the same tag. To retrieve the second item in a list (characters in our example):
The character[1] statement above instructs PHP to use the second (0 was the first) occurrence of character. The Output:
(Iteration Reading) Accessing XML Data (Attributes and Children) via itteration
It is easy to loop through the data of an XML document even if you don't know the names of the attributes.
Using XPath to Access Data
XPath is the XML Path Language. It is a query language that allow you to select nodes in an XML document. SimpleXML comes with a function which makes using and accessing nodes extremely easy.
xpath() allows you to enter a path just as you would enter a folder/directory path structure. Here is an example from our XML file above:
Print the output out with print_r or var_dump and you'll see:
Searching
XPath allows you to search making it even easier to use. To search, use a double slash instead of a single slash. This tells XPath to search for tags containing your data.
Print_r:
Conclusion
This was a simple tutorial which instructed you how to load and access the elements of an XML file using SimpleXML. Since it became so long, I decided to stop with reading. Writing will be left for another tutorial in the future.
Full Code
If you have any questions, feel free to ask here or in PHP section on QuestionBin.
Creating the Object
Lets start by creating the SimpleXML object. You can create it by loading from a string or loading from a file.
Loading from String:
PHP Code:
// Create an XML Document String
$xmlStr = <<<XML
<?xml version="1.0" standalone="yes"?>
<movies>
<movie>
<title>PHP: Behind the Parser</title>
<characters>
<character>
<name>Ms. Coder</name>
<actor>Onlivia Actora</actor>
</character>
<character>
<name>Mr. Coder</name>
<actor>El Actor</actor>
</character>
</characters>
<plot>
So, this language. Its like, a programming language. Or is it a
scripting language? All is revealed in this thrilling horror spoof
of a documentary.
</plot>
<great-lines>
<line>PHP solves all my web problems</line>
</great-lines>
<rating type="thumbs">7</rating>
<rating type="stars">5</rating>
</movie>
</movies>
XML;
$xmlStr = <<<XML
<?xml version="1.0" standalone="yes"?>
<movies>
<movie>
<title>PHP: Behind the Parser</title>
<characters>
<character>
<name>Ms. Coder</name>
<actor>Onlivia Actora</actor>
</character>
<character>
<name>Mr. Coder</name>
<actor>El Actor</actor>
</character>
</characters>
<plot>
So, this language. Its like, a programming language. Or is it a
scripting language? All is revealed in this thrilling horror spoof
of a documentary.
</plot>
<great-lines>
<line>PHP solves all my web problems</line>
</great-lines>
<rating type="thumbs">7</rating>
<rating type="stars">5</rating>
</movie>
</movies>
XML;
PHP Code:
// Load an XML string
$xml = simplexml_load_string($xmlstr);
$xml = simplexml_load_string($xmlstr);
PHP Code:
// Load an XML string by passing
// it to the construction of the class
$xml = new SimpleXMLElement($xmlStr);
// it to the construction of the class
$xml = new SimpleXMLElement($xmlStr);
Loading from a File:
Again, there are two ways to create the object from a file and again one involves a function and the other uses the OOP constructor. Lets take a look at the function first. Loading a file using simplexml_load_file() is easy, you only need to pass the XML file path to the function:
PHP Code:
// Load an XML File
$xml = simplexml_load_file('myXMLDocument.xml');
$xml = simplexml_load_file('myXMLDocument.xml');
Using the Constructor:
Using the construction to load an XML document is fast and efficient:
PHP Code:
// Load an XML File
$xml = new SimpleXMLElement('myXMLDocument.xml', NULL, true);
$xml = new SimpleXMLElement('myXMLDocument.xml', NULL, true);
The Object - Simple XML Reading
The SimpleXMLElement object is an array of SimpleXMLElement objects. You use them as such. To access elements, you only need to supply the tag name:
PHP Code:
echo $xml->movie->title;
Access the Second Object where there are multiple items
Use the object just as you would an array when there are multiple occurrences of the same tag. To retrieve the second item in a list (characters in our example):
PHP Code:
$xml->movie->characters->character[1]->name;
Code:
Mr. Coder
It is easy to loop through the data of an XML document even if you don't know the names of the attributes.
PHP Code:
// Create a simpleXML element
$xml = new SimpleXMLElement ( $xmlstr );
// Loop through the document
foreach ( $xml->children () as $child ) {
echo $child->getName () . "\n";
// Loop through the child documents
// of $child
foreach ($child->children() as $kid) {
echo "Name: " . $kid->getName() . "\n";
echo "Value: " . $kid . "\n";
echo "Attributes: " . $kid->attributes() . "\n\n";
}
}
$xml = new SimpleXMLElement ( $xmlstr );
// Loop through the document
foreach ( $xml->children () as $child ) {
echo $child->getName () . "\n";
// Loop through the child documents
// of $child
foreach ($child->children() as $kid) {
echo "Name: " . $kid->getName() . "\n";
echo "Value: " . $kid . "\n";
echo "Attributes: " . $kid->attributes() . "\n\n";
}
}
Using XPath to Access Data
XPath is the XML Path Language. It is a query language that allow you to select nodes in an XML document. SimpleXML comes with a function which makes using and accessing nodes extremely easy.
xpath() allows you to enter a path just as you would enter a folder/directory path structure. Here is an example from our XML file above:
PHP Code:
$xml->xpath("/movies/movie");
Code:
Array ( [0] => SimpleXMLElement Object ( [title] => PHP: Behind the Parser [characters] => SimpleXMLElement Object ( [character] => Array ( [0] => SimpleXMLElement Object ( [name] => Ms. Coder [actor] => Onlivia Actora ) [1] => SimpleXMLElement Object ( [name] => Mr. Coder [actor] => El Actor ) ) ) [plot] => So, this language. Its like, a programming language. Or is it a scripting language? All is revealed in this thrilling horror spoof of a documentary. [great-lines] => SimpleXMLElement Object ( [line] => PHP solves all my web problems ) [rating] => Array ( [0] => 7 [1] => 5 ) ) )
XPath allows you to search making it even easier to use. To search, use a double slash instead of a single slash. This tells XPath to search for tags containing your data.
PHP Code:
$xml->xpath("//plot");
Code:
Array ( [0] => SimpleXMLElement Object ( [0] => So, this language. Its like, a programming language. Or is it a scripting language? All is revealed in this thrilling horror spoof of a documentary. ) )
Conclusion
This was a simple tutorial which instructed you how to load and access the elements of an XML file using SimpleXML. Since it became so long, I decided to stop with reading. Writing will be left for another tutorial in the future.
Full Code
PHP Code:
<?php
// Create an XML Document String
$xmlStr = <<<XML
<?xml version="1.0" standalone="yes"?>
<movies>
<movie>
<title>PHP: Behind the Parser</title>
<characters>
<character>
<name>Ms. Coder</name>
<actor>Onlivia Actora</actor>
</character>
<character>
<name>Mr. Coder</name>
<actor>El Actor</actor>
</character>
</characters>
<plot>
So, this language. Its like, a programming language. Or is it a
scripting language? All is revealed in this thrilling horror spoof
of a documentary.
</plot>
<great-lines>
<line>PHP solves all my web problems</line>
</great-lines>
<rating type="thumbs">7</rating>
<rating type="stars">5</rating>
</movie>
</movies>
XML;
// Load an XML string by passing
// it to the construction of the class
$xml = new SimpleXMLElement($xmlStr);
echo $xml->movie->characters->character[1]->name;
echo "<pre>";
print_r($xml->xpath("//plot"));
echo "</pre>";
// Create an XML Document String
$xmlStr = <<<XML
<?xml version="1.0" standalone="yes"?>
<movies>
<movie>
<title>PHP: Behind the Parser</title>
<characters>
<character>
<name>Ms. Coder</name>
<actor>Onlivia Actora</actor>
</character>
<character>
<name>Mr. Coder</name>
<actor>El Actor</actor>
</character>
</characters>
<plot>
So, this language. Its like, a programming language. Or is it a
scripting language? All is revealed in this thrilling horror spoof
of a documentary.
</plot>
<great-lines>
<line>PHP solves all my web problems</line>
</great-lines>
<rating type="thumbs">7</rating>
<rating type="stars">5</rating>
</movie>
</movies>
XML;
// Load an XML string by passing
// it to the construction of the class
$xml = new SimpleXMLElement($xmlStr);
echo $xml->movie->characters->character[1]->name;
echo "<pre>";
print_r($xml->xpath("//plot"));
echo "</pre>";
No comments posted
