home community downloads matrix search newsjoinmembers: 4815
joomla wordpress drupal smiletag fireorb java php ruby classic ASP
 videos
 articles
 blogs
 comments
 downloads
sitemap
Sun, 2008-05-04 17:57
PHP

In the last few weeks while looking for a position as a PHP programmer I have received several standard replies. One of them was "Can you go to our web site and answer the questions on PHP 5 and XML? Though I never give replies like these any place in my mind. I did feel the necessity to look into the latest features of PHP5 SimpleXML. I saw that many things have changed since I tried handling XML in PHP. To be honest I found the PHP4 methods to be really sucky. I found myself using these huge classes with a method to cover each and every small change in the XML. SimpleXML looks to be a much better choice and seems to be getting better with each version.

The SimpleXML extension provides a very simple and easily usable toolset to convert XML to an object that can be processed with normal property selectors and array iterators. You can read, write or iterate over your XML file with ease accessing elements and attributes.

Export and Import

The opening of XML file is possible with the function simplexml_load_file (). It takes in parameter URI or URL and returns an object of the class simpleEMLElement.

Example: $xml = simplexml_load_file(pathway or URL);

It’s also possible to interpret a string of XML into an object with simplexml_load_string (). This function will take the well-formed xml string data and return an object of class SimpleXMLElement with properties containing the data held within the xml document. If any errors occur, it returns FALSE.

Example:

Export and save of XML code

It’s possible to save a part or totality of a XML document with the asXML function. For that, the asXML method formats the parent object's data in XML, or of course a node of document XML. It returns the contents of a file XML in a character string or directly in a file.
Example 1: Export of data in a variable

<?php

    $xml 
simplexml_load_file("movies.xml");
    
$string $xml->asXML();
  
print_r($string);

?>

Example2: To save in a file

<?php

  $xml 
simplexml_load_file ("movies.xml");
  
$xml->asXML ("child.xml");
  
$xml simplexml_load_file("child.xml");
  
$string $xml->asXML();
  print 
'<h1> The child file is loaded</h1>';
  
print_r($string);

?>

Handling of elements

The parsing of data in XML is also very simple.

I'll make an example in order to illustrate the handling of elements.

Example of file data in 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 Act&#211;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's 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>
<movie>
  <title>PHP 5: A New World</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Zev Zend</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#211;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's 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>

To access the node by name

There are several cases to access to node. To access to only one node the following code is used:

<?php

  $xml 
simplexml_load_file ("movies.xml");
  
$movie $xml->movie;
  
$title $movie->title;
  print (
$title).'<br>';
                              
// lets go a bit deeper and get a famous line to see what the code looks like
                              // the element "great-lines" is a valid xml name but the "-" will create a problem so it needs to be encapsulated
  
$movie $xml->movie;
  
$line $movie->{'great-lines'}->line;
                              print (
$line).'<br>';
?>

This script will display:

"PHP:Behind the parser"

“PHP solves all my web problems”.

This is because although the code is valid it does not say which parent element to start with so XML and PHP default to the first in the list. Also take notice of the "great-lines" element. XML allows "-" within names but the PHP SimpleXML parser does not recognize it as valid without a little help. The string needs to be encapsulated within the code call.

<?php

$line 
$movie->{'great-lines'}->line;
?>

In this example XML we have a file containing several tags “album”, we can display the first tag album or to list all the albums. For that we use the following code:

<?php

  $xml 
simplexml_load_file ("movies.xml");
  
//display of the  second movie.
                              
$premier_movie $xml->movie [1];
  print 
'<p>'.$premier_movie->title.'</p>';
  
//all the albums are listed
                              
print '<ul>';                            foreach ($xml->movie  as  $movie){
                                  print 
'<li>'.$movie->title.'</li>';
    }
                              print 
'</ul>';
?>

This example will display:

PHP 5: A New World

  • PHP: Behind the Parser
  • PHP 5: A New World

To access given nodes

To find children of given node the function children is used (). I don't need to know the name of nodes. This method finds the children of the element of which it is a member.

To display the single first element the XML tree:

<?php

          $xml 
simplexml_load_file ("movies.xml");
          
$movies $xml->movie;
          
$elements $movies->children();
          print 
'<p>'.$elements[0].'</p>';

?>

To display multiple children of an element:

<?php

          $xml 
simplexml_load_file ("movies.xml");
          
$movies $xml->movies;
          
$great_lines $movie->{'great-lines'}[0];
          foreach (
$great_lines as $line => $string){
              print   
"<p>the tag $line contains $string</p>";
          }

?>

Handling values

One of the nice things about how PHP does XML is that the values in a file do not have to be constant or permanent. You can change them and save those changes to a new file. I found this to be interesting having come from ASP and the use of Excel files as a data source. Manipulation of data in an excel file is a pain. But doing something similar in PHP5 and XML is cake.

<?php

  $xml 
simplexml_load_file ("movies.xml");
  
$movies $xml->movies;
    print 
'<p>'.$xml->movie[0]->characters->character[0]->name.'</p>' ;
  
$xml->movie[0]->characters->character[0]->name 'Miss Xoder';
  print 
'<p>'.$xml->movie[0]->characters->character[0]->name '</p>';

?>

Handling of the attributes

To access to an attribute, it is very simple. In our example we have tags albums with the attribute language, thus $xml [“rating”], with $xml the object representing our file XML, is an associative table of the attributes rating.

To list all the attributes of a node it is necessary to use the function attributes (). This function returns us an associative table with all the attributes out of key and the value associated.

Example 1:

<?php

  $xml 
simplexml_load_file ("movies.xml");
    
/* Access the <rating> nodes of the first movie.
 * Output the rating scale, too. */
foreach ($xml->movie[0]->rating as $rating) {
    switch((string) 
$rating['type']) { // Get attributes as element indices
    
case 'thumbs':
        print 
$rating .  ' thumbs up<br>';
        break;
    case 
'stars':
        print 
$rating .  ' stars';
        break;
    }
}

?>

Updating, Adding and Removing

Now comes a good reason for keeping your PHP version updated to the latest one possible. Doing the following was not possible with PHP 5.13 or PHP 4 without getting into some heavy string manipulation code.

Example2:

<?php

  $xml 
simplexml_load_file ("movies.xml");
  
$movies $xml->movies;
  
$character $xml->movie[0]->characters->addChild('character');
  
$character->addChild('name''Mr. Parser');
  
$character->addChild('actor''John Doe');
  
$rating $xml->movie[0]->addChild('rating''PG');
  
$rating->addAttribute('type''mpaa');
  print 
$xml->asXML();

?>

So if anyone starts giving you a hard time about wanting the latest version of PHP tell them to stick it! At my present job one of the reasons that I am happily looking for different employment is because to their constant need to get things done quickly be refusal to at least try and use PHP5.


Happy Publishing!

Social sharing: delicious  digg  reddit  icerocket
php's picture
Join Hiveminds and link to your website or blog.
 
 

Newsletter

Get updates on Hiveminds services, articles and downloads by signing up for the newsletter.

Editor's choice

Some of the better articles, stories and tutorials found at Hiveminds.

Find more

Find more of Hiveminds articles, stories, tutorials and user comments by searching.




Picked links

Hand picked websites and articles from around the web that provide quality reading.

page top