Hi.
I'm taking my first tests with DOM Functions
(I found it very useful 😃 )
I've got this simple snippet:

<?php 
class mXml extends DomDocument {
    public function __construct() {
        //has to be called!
        parent::__construct();
    }
    public function addArticle($title) {
		$this->load("articles.xml");
        $item = $this->createElement("item");
        $titlespace = $this->createElement("title");
        $titletext = $this->createTextNode($title);
        $titlespace->appendChild($titletext);
        $item->appendChild($titlespace);
        $this->documentElement->appendChild($item);
		$this->save("articles.xml");
    }
	public function displayXml()
	{
		$this->load("articles.xml");
	  	$titles = $this->getElementsByTagName("title");
		foreach($titles as $node) {
   		print $node->textContent . "\n";
		} 
	}

} 
$dom = new mXml();
$dom->addArticle("XML in PHP5"); 
$dom->addArticle("XML in PHP6"); 
$dom->addArticle("XML in PHP7"); 
$dom->displayXml();
?>

My start xml file:

<?xml version="1.0" encoding="utf-8"?>
<items>
</items> 

I'm wondering is it the right way ?
Thanks in advance.

Bye.

    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.

      I feel that a method which uses less code is better.

      The first example is alright, although I wouldn't extend DomDocument- it seems a little bit unnecessary. Creating a class which simply encapsulates a DomDocument would seem more logical.

      Also, you might want to separate your methods to add, load, save and display, rather than doing a save whenever an article is added. This would be more optimal, e.g. if you wanted to add several articles in one operation.

      Mark

        Thanks so much buddy.

        The first example is alright, although I wouldn't extend DomDocument- it seems a little bit unnecessary. Creating a class which simply encapsulates a DomDocument would seem more logical.

        I agree with you I made the latter only to avoid chmod troubles.

        Also, you might want to separate your methods to add, load, save and display, rather than doing a save whenever an article is added. This would be more optimal, e.g. if you wanted to add several articles in one operation.

        Ok I'm posting an other snippet.

        Bye.

          <?php 
          class DocLoader {
          	public $doc = null;
          	public function __construct() {
                	$this->doc = new DOMDocument();
          	}
          	public function loadXmlFile($fileName,$className) {
          		if(!is_file($fileName)){
                      throw new Exception('Invalid file name ['.$fileName.']');
                  }
          		if(!$this->doc->load($fileName)) {
                      throw new Exception('Error loading file ['.$fileName.']');
                  }
          		if (!class_exists($className)) {
          		   throw new Exception('Error loading class ['.$className.']');
          		}
          		return new $className($this->doc);
          	}
          }
          class DocArticles
          {
          	public $doc = null;
          	public function __construct($doc) {
                	$this->doc = $doc;
          	}
          	public function addElement($title) {
          	 	$item = $this->doc->createElement("item");
          		$titlespace = $this->doc->createElement("title");
          		/* utf8_encode to managing special characters.In my case (è,à,ò,ì)*/
                  $titletext = $this->doc->createTextNode(utf8_encode($title));
                  $titlespace->appendChild($titletext);
                  $item->appendChild($titlespace);
          		$this->doc->documentElement->appendChild($item);
          	}
          	public function save($fileName) {
          		if(!$this->doc->save($fileName)){
          		 	throw new Exception('Error saving file ['.$fileName.']');
          		}
          	}
          	public function display()
          	{
          		$titles = $this->doc->getElementsByTagName("title");
          		foreach($titles as $node) {
             			print '<p>'.htmlentities($node->firstChild->data,ENT_QUOTES,'UTF-8') . "</p>\n";
          		} 
          	}
          	public function removeChild($itemNum)
          	{
          		$root = $this->doc->documentElement;
          		$item = $root->getElementsByTagName("item");
          		if(is_null($item->item((int)$itemNum))) {
          			throw new Exception('Error removing item ['.$itemNum.']');
          		}
          		$root->removeChild($item->item((int)$itemNum));
          	}
          }
          try {
          	$doc = new DocLoader();
          	$docArticles = $doc->loadXmlFile('xml/articles.xml','DocArticles');
          	$docArticles->addElement("lllàèò+ò''XML in PHP5");
          	$docArticles->addElement("lllàèò+ò''XML in PHP6");
          	$docArticles->addElement("lllàèò+ò''XML in PHP7");
          	$docArticles->removeChild(0);
          	$docArticles->display();
          	$docArticles->save('xml/articles.xml');
          }
          catch(Exception $e){
              echo $e->getMessage();
              exit();
          }
          
          ?>
          

          What do you think about ?

          The only hassle to follow this way is
          to set permission by my host control panel.

          Bye.

            <?php 
            class XmlLoader {
            	public $doc = null;
            	public function __construct() {
                  	$this->doc = new DOMDocument();
            	}
            	public function loadXmlFile($fileName) {
            		if(!is_file($fileName)){
                        throw new Exception('Invalid file name ['.$fileName.']');
                    }
            		if(!$this->doc->load($fileName)) {
                        throw new Exception('Error loading file ['.$fileName.']');
                    }
            		return new XmlParser($this->doc);
            	}
            }
            class XmlParser
            {
            	public $doc = null;
            	private $_item = '';
            	public function __construct($doc) {
                  	$this->doc = $doc;
            		$this->_item = 'item';
            	}
            	public function addElement($xmlBody) {
            	 	$item = $this->doc->createElement($this->_item);
            		foreach($xmlBody as $key => $value) {
            			$nodespace = $this->doc->createElement($key);
            			$nodetext = $this->doc->createTextNode($value);
            			$nodespace->appendChild($nodetext);
            			$item->appendChild($nodespace);
            		}
            		$this->doc->documentElement->appendChild($item);
            	}
            	public function getUpdatedValue($itemNum)
            	{
            		$values=array();
            		$item = $this->doc->getElementsByTagName("item");
            		if(is_null($selected=$item->item((int)$itemNum))) {
            			throw new Exception('Error removing item ['.$itemNum.']');
            		}
            		foreach ($selected->childNodes as $elements) {
              			if ($elements->nodeType == 1 ) {
            				if($elements->firstChild->nodeType == 3) {
            					$values[] = $elements->firstChild->data;
            				}
            				}
            		}
            		return $values;
            
            }
            public function removeChild($itemNum)
            {
            	$item = $this->doc->getElementsByTagName("item");
            	if(is_null($item->item((int)$itemNum))) {
            		throw new Exception('Error removing item ['.$itemNum.']');
            	}
            	$this->doc->documentElement->removeChild($item->item((int)$itemNum));
            }
            public function replaceChild($xmlBody,$itemNum)
            {
            	$item = $this->doc->createElement($this->_item);
            	foreach($xmlBody as $key => $value) {
            		$nodespace = $this->doc->createElement($key);
            		$nodetext = $this->doc->createTextNode($value);
            		$nodespace->appendChild($nodetext);
            		$item->appendChild($nodespace);
            	}
            	$root = $this->doc->documentElement;
            	$selected = $root->getElementsByTagName("item");
            	if(is_null($selected->item((int)$itemNum))) {
            		throw new Exception('Error replacing item ['.$itemNum.']');
            	}
            	$oldnode = $selected->item((int)$itemNum);
            	$newnode = $this->doc->importNode($item, true);
            	$oldnode->parentNode->replaceChild($newnode, $oldnode);
            }
            public function save($fileName) {
            	if(!$this->doc->save($fileName)){
            	 	throw new Exception('Error saving file ['.$fileName.']');
            	}
            }
            public function getItemElements()
            {
            	$item=array();
            	foreach ($this->doc->documentElement->childNodes as $elements) {
            		if ($elements->nodeType == 1 ) {
            			$item[] = $elements;
            		}
            	} 
            	return $item;
            }
            public function getNodesValue($item)
            {
            	$values=array();
            	foreach ($item->childNodes as $elements) {
            		if ($elements->nodeType == 1 ) {
            			if($elements->firstChild->nodeType == 3) {
            				$values[] = $elements->firstChild->data;
            			}
            			}
            	}
            	return $values;
            }
            }//
            ?>
            

            A simple appliance http://www.blogial.net/index.php?view=11.
            in italian but it speaks PHP 😉 .

            xml structure example:

            <items>
            	<item>
            		<time>
            		</time>
            		<title>
            		</title>
            		<author>
            		</author>
            		<content>
            		</content>
            	</item>;
            </items>
            

            Bye.

              Write a Reply...