PHP – Class XML Writer

This PHP class can write XML documents to files.

It can open a given file and writes XML tags and data to it.

The class can write XML header tags, open and close tags, single elements with tag and data, and�
lists of elements from an associative array.

Code Example: Download Example
index.php
<?php
require_once 'XMLFile.php';

$xml_file = "test.xml";

$x = new XMLFile();
$x->open($xml_file);
$x->writeHeader();

$x->writeOpenTag('PHONE_BOOK','');
	$x->writeOpenTag('INDEX_Q','');
    	$x->writeElement('NAME','','QASIM');
        $x->writeElement('PHONE','','111-111-1111');
		$x->writeElement('ADDRESS','','123 M St.');
        $x->writecloseTag('INDEX_Q');
	$x->writecloseTag('PHONE_BOOK');
$x->close();

echo  file_get_contents($xml_file);
?>
XMLFile.php
<?php
class XMLFile
{
  private $fd = 0;

  function __destruct()
  {
    $this->close();
  }

  public function open($name)
  {
    $this->fd = fopen($name,'w');
  }

  public function forceopen($name)
  {
    $this->fd = fopen($name,'w+');
  }
  public function close()
  {
    if ($this->fd)
    {
      fclose($this->fd);
      $this->fd = 0;
    }
  }

  public function writeText(&$text)
  {
    fwrite($this->fd, htmlspecialchars($text));
  }

  public function writeOpenTag($tagname,$attrs='')
  {
    if (strlen($attrs)) $attrs = " $attrs ";
    fwrite($this->fd, "<$tagname$attrs>\n");
  }

  public function writeElement($tagname, $attrs='', $value='')
  {
    if (strlen($attrs)) $attrs = " $attrs ";
    if (strlen($value))
    {
      fwrite($this->fd, "<$tagname$attrs>".htmlspecialchars($value)."<$tagname>\n");
    }
    else
    {
      fwrite($this->fd, "<$tagname$attrs/>\n");
    }
  }

  public function writeArray($arr, $rootName)
  {
       if ($rootName != ""){
        $root = $rootName;
        }else{
         $root = "root";
        }

      if (!is_array($arr) && count($arr) == 0) { return false;}

				fwrite($this->fd, "<$rootName>\n");

					foreach ($arr as $key => $val){

					    if (is_array($val)) {
                   $this->writeArray($val,$key);
              }else{
					         fwrite($this->fd, "<$key>".htmlspecialchars($val)."</$key>\n");
              }
					}
			  fwrite($this->fd, "</$rootName>\n");

  }

  public function writeWord($tagname)
  {
    fwrite($this->fd, "$tagname\n");
  }

  public function writeCloseTag($tagname)
  {
    fwrite($this->fd, "<$tagname>\n");
  }

  public function writeHeader()
  {
    fwrite($this->fd, '<?xml version="1.0" encoding="ISO-8859-1"?>');
    fwrite($this->fd, "\n");
  }

}
?>

Post to Twitter Post to Digg Post to Facebook Post to Google Buzz Send Gmail

Leave a Comment

Your email address will not be published. Required fields are marked *