An other way I think it's far better
<?php
class MFS
{
public static function getPath()
{
$path = dirname(__FILE__);
$path = str_replace('\\', '/', $path);
return $path.'/';
}
public static function mk_dir($dirName,$rights = 0777)
{
$path = self::getPath();
if(!is_dir($dirName))
{
if(!@mkdir($path.$dirName,$rights))
{
throw new Exception("It\'s impossible to create ".$dirName);
}
}
return $path;
}
}//
class xmlFileBuilder extends DomDocument
{
const RIGHTS = 0700;
const DIR_NAME = 'xml/';
const FORMAT_OUT_PUT = true;
protected $_path = '';
public function __construct($stringVersion,$stringEncoding)
{
parent::__construct($stringVersion,$stringEncoding);
$this->_path = MFS::mk_dir(self::DIR_NAME,self::RIGHTS).self::DIR_NAME.'/';
}
public function buildXmlFile($rootElement,$fileName)
{
if(!file_exists($this->_path.$fileName))
{
$this->formatOutput = self::FORMAT_OUT_PUT;
$rootElement = parent::createElement($rootElement, '');
parent::appendChild($rootElement);
if(!parent::save($this->_path.$fileName))
{
throw new Exception("It\'s impossible to create ".$fileName);
}
}
}
}//
class xmlBodyBuilder extends xmlFileBuilder
{
const ROOT_ELEMENT = 'articles';
const FILE_NAME = 'articles.xml';
public function __construct($stringVersion,$stringEncoding)
{
parent::__construct($stringVersion,$stringEncoding);
parent::buildXmlFile(self::ROOT_ELEMENT,self::FILE_NAME);
}
public function addArticle($title) {
$this->load($this->_path.self::FILE_NAME);
$this->formatOutput = parent::FORMAT_OUT_PUT;
$item = $this->createElement("item");
$titlespace = $this->createElement("title");
$titletext = $this->createTextNode($title);
$titlespace->appendChild($titletext);
$item->appendChild($titlespace);
$this->documentElement->appendChild($item);
$this->save($this->_path.self::FILE_NAME);
}
public function displayXml()
{
$this->load($this->_path.self::FILE_NAME);
$titles = parent::getElementsByTagName("title");
foreach($titles as $node) {
print $node->textContent . "\n";
}
}
}//
$dom = new xmlBodyBuilder('1.0', 'utf-8');
$dom->addArticle("XML in PHP5");
$dom->addArticle("XML in PHP6");
$dom->addArticle("XML in PHP7");
$dom->displayXml();
?>
Are there any mistake ?
What do you think about ?
Bye.