Friday 3 December 2010

PHP: Working with XML

In this article I'll implement base functions to interact with XML like: loading, showing, saving, adding, deleting, editing.

My XML document sample:
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<spectacle>
<image>images/8780_185540_img2.jpg</image>
<date>16.09.10</date>
<time>19:00</time>
<title>Hamlet</title>
<author>W.Shakespeare</author>
<genre> tragedy</genre>
</spectacle>
</catalog>
HTML action :
<form method="post" action="begin.php" name="adminForm" >

Exists 3 methods in PHP 5 which allow us to interact with XML: DOM, Simple XML and XPath.

The simplest way is to use Simple XML :). But it have and disadvantages when you need more methods to interact with XML, in this cases you may use DOM.

When you want to get an element use:
$catalog->spectacle[0]; //return sprectacle
When you want to get an attribute use:
$image['att_name'];
When you want to get data use:
echo ($xml->catalog->spectacle[0]->title);

So here is my source code:
$spectacles = Array();
/*add to xml specified spectacle node*/
function addToXml()
{
  $xml = simplexml_load_file("catalog.xml"); //This line will load the XML file. 

  $sxe = new SimpleXMLElement($xml->asXML());  
  //The following lines will add a new child 
  $spectacle = $sxe->addChild("spectacle"); 
  $spectacle->addChild("image", $_POST["image"]); 
  $spectacle->addChild("date", $_POST["date"]); 
  $spectacle->addChild("time", $_POST["time"]); 
  $spectacle->addChild("title", $_POST["title"]); 
  $spectacle->addChild("author", $_POST["author"]); 
  $spectacle->addChild("genre", $_POST["genre"]);  
  
  //use for format output
  $dom = new DOMDocument('1.0');
  $dom->preserveWhiteSpace = false;
     $dom->formatOutput = true;
  $dom->loadXML($sxe->asXML());
     $dom->saveXML();
  $dom->save("catalog.xml");
}
/*loading xml to global array*/
function loadXML()
{ 
   global $spectacles;

    $xml = simplexml_load_file("catalog.xml");
 
 foreach($xml->spectacle as $spectacle)
    {
     array_push($spectacles, $spectacle);
  
    }
}
/*showing xml in table view*/
function showXML()
{
   //print_r($spectacles);
   global $spectacles;
   echo "<table border='1'><tr>";
   echo "<td>Image</td>";
   echo "<td>Date</td>";
   echo "<td>Time</td>";
   echo "<td>Title</td>";
   echo "<td>Author</td>";
   echo "<td>Genre</td>";
   echo "</tr>\n";
    
 foreach ($spectacles as $spectacle) 
 { 
      echo "<tr>";   
      echo "<td>".$spectacle->image."</td>"; 
      echo "<td>".$spectacle->date."</td>"; 
      echo "<td>".$spectacle->time."</td>"; 
      echo "<td>".$spectacle->title."</td>"; 
      echo "<td>".$spectacle->author."</td>"; 
      echo "<td>".$spectacle->genre."</td>"; 
      echo "</tr>\n";
 }
 echo "</table";
}

/*delete node with specified date & title*/
function deleteNodeXML()
{
   global $spectacles;
   $spectacle_final = Array();

   foreach($spectacles as $spectacle)
   {
  if($spectacle->date != $_POST['date'] && $spectacle->title != $_POST['title'])
  {
   array_push($spectacle_final, $spectacle);
  }
 }
 saveDom($spectacle_final); //saving our array to xml
}

/*edit node with specified date & title*/
function editXml()
{
   global $spectacles;
   $spectacle_final = Array();

   foreach($spectacles as $spectacle)
   {
  if($spectacle->date == $_POST['date'] && $spectacle->title == $_POST['title'])
  {
      $spectacle->image = $_POST['imageNew'];
            $spectacle->date = $_POST['dateNew'];
   $spectacle->time = $_POST['timeNew'];
   $spectacle->title = $_POST['titleNew'];
   $spectacle->author = $_POST['authorNew'];
   $spectacle->genre = $_POST['genreNew'];
   
   array_push($spectacle_final, $spectacle);
  }
  else 
  {
   array_push($spectacle_final, $spectacle);
  }
 }
 saveDom($spectacle_final); //saving our array to xml
}

/*saving array to xml*/
function saveDom($spectacle_final)
{
    $doc = new DOMDocument('1.0','UTF-8');
 $doc->encoding='UTF-8';
 
 // we want a nice output
 $doc->formatOutput = true;

 $root = $doc->createElement('catalog');
 $root = $doc->appendChild($root);

 foreach($spectacle_final as $spectacle)
 { 
  $spect = $doc->createElement('spectacle');
  $spect = $root->appendChild($spect);

  $imag = $doc->createElement('image');
  $imag = $spect->appendChild($imag);  
  $text = $doc->createTextNode($spectacle->image);
  $text = $imag->appendChild($text);
  
  $dat = $doc->createElement('date');
  $dat = $spect->appendChild($dat);  
  $text = $doc->createTextNode($spectacle->date);
  $text = $dat->appendChild($text);
  
  $tim = $doc->createElement('time');
  $tim = $spect->appendChild($tim);  
  $text = $doc->createTextNode($spectacle->time);
  $text = $tim->appendChild($text);
  
  $tit = $doc->createElement('title');
  $tit = $spect->appendChild($tit);  
  $text = $doc->createTextNode($spectacle->title);
  $text = $tit->appendChild($text);
  
  $aut = $doc->createElement('author');
  $aut = $spect->appendChild($aut);  
  $text = $doc->createTextNode($spectacle->author);
  $text = $aut->appendChild($text);
  
  $gen = $doc->createElement('genre');
  $gen = $spect->appendChild($gen);  
  $text = $doc->createTextNode($spectacle->genre);
  $text = $gen->appendChild($text);
 }

   $doc->saveXML() . "\n"; 
   $doc->save("catalog.xml");
}

References: 

Using XML: A PHP Developer's Primer
Official php documentation

No comments:

Post a Comment