Ask
 
Answer
 
Forum
 
Debate
 
Blog
 
Categories
Entertainment & Music

Computers

Internet

Science & Mathematics

Health

Consumer Electronics

Sports

Society & Culture

Food & Drink

Education & Reference

 
More >>

 
Sign Up
Languages
English

Finnish

Arabic

Italian

Korean

French

Chinese(Traditional)

Chinese(Simplified)

Swedish

Czech

Hindi

Dutch

Norwegian

Russian

Croatian

German

Japanese

Bulgarian

Portuguese

Chinese

Spanish

Greek

 
Login


Remember:
Signin With:
 
OpenID

Google

Yahoo!

Facebook

Ning

 

Ok

Ask a Question



Search

Advanced

Topics

code computer difference download facebook file game internet justin linux money mysql name number online page php poptropica someone something system time ubuntu way web wii windows wordpress world year

More >>

Categories

  • ■Computers (19078) Subcategory Available
  • ■Internet (14465) Subcategory Available
  • ■Entertainment & Music (10042) Subcategory Available
  • ■Health (6866) Subcategory Available
  • ■Programming (6748) Subcategory Available
  • ■Video & Online Games (4994) Subcategory Available
  • ■Science & Mathematics (4123) Subcategory Available
  • ■Business & Finance (3899) Subcategory Available
  • ■Politics & Government (1666) Subcategory Available
  • ■Arts & Humanities (1653) Subcategory Available

More >>

Question Library

# A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
  • Manage Blogs
  • Add Blog
  • All Blogs

 

 

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: 

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;
PHP Code:
// Load an XML string
$xml = simplexml_load_string($xmlstr);  
Alternatively you can pass a string to the constructor of the class (example blow using the XML String from above):

PHP Code:
// Load an XML string by passing
// 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');  

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);  
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:

PHP Code:
echo $xml->movie->title;  
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):

PHP Code:
$xml->movie->characters->character[1]->name;  
The character[1] statement above instructs PHP to use the second (0 was the first) occurrence of character. The Output:
Code:
Mr. Coder
(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.

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"; 
    }
}  

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");  
Print the output out with print_r or var_dump and you'll see:

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
)
)
)
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.

PHP Code:
$xml->xpath("//plot");  
Print_r:
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>";
If you have any questions, feel free to ask here or in PHP section on QuestionBin. 


  • Total views:  1581
  • Total comments:  0
  • Tick This

Rate Now: 1 2 3 4 Average Rating: 4.00 / 1 ratings

No comments posted

Disclaimer | Privacy Policy | Terms | Report Bugs | ■ RSS | Sitemap | Contact Us | ■ Invite | Create your Widget | ■ Twitter
■ Howto Tutorials | ■ Linux Questions | ■ Social Bookmarking | ■ Game Forums ■ Game Glitches/Hacks ■ Technology Blog ■ Money Blog

© 2009 QuestionBin. All rights reserved

QuestionBin does not evaluate or guarantee the accuracy of any QuestionBin content. Click here for the Full Disclaimer.