Jump to content

DOMDocument


Andy-H

Recommended Posts

Does anyone know if DOMDocument allows you to call getElementById on the id of an element that has been inserted into the DOM (in my case, via DOMDocumentFragment) since instantiation?

 

 

It doesn't find the element if I try to select a newly inserted element, but works fine if its from the original template:

Template.class.php


<?php
namespace phantom\classes\templating;
class Template {
   protected $_document;
   protected $_settings = array(
      'version'      => '4.01',
      'encoding'     => 'UTF-8',
      'template_dir' => 'templates',
      'template_ext' => 'tmpl.php'
   );
   
   public function __construct($tmpl_file, array $data = array(), array $settings = array())
   {
      $this->_settings = array_merge($this->_settings, $settings);
      $this->_document = new \DOMDocument($this->_settings['version'], $this->_settings['encoding']);
      $this->_document->loadHTML($this->_getContent($tmpl_file, $data));
   }
   public function getFragment($file_name, array $data = array())
   {
      return new TemplateFragment($this->_getContent($file_name, $data), $this->_document);
   }
   public function getContents()
   {
      return $this->_document->saveHTML();
   }
   protected function _getContent($file_name, array $data = array())
   {
      ob_start();
      extract($data, EXTR_SKIP);
      include $this->_settings['template_dir'] . DIRECTORY_SEPARATOR . $file_name .'.'. $this->_settings['template_ext'];
      return ob_get_clean();
   }
}

TemplateFragment.class.php


<?php
namespace phantom\classes\templating;
class TemplateFragment {
   protected $_content;
   protected $_document;
   
   public function __construct($content, \DOMDocument $document)
   {
      $this->_document = $document;
      $this->_content  = $this->_document->createDocumentFragment();
      $this->_content->appendXML($content);
   }
   public function insertBefore($selector)
   {
      $node = $this->_getElement($selector);
      $node->parentNode->insertBefore($this->_content, $node);
   }
   public function insertAfter($selector)
   {
      $node = $this->_getElement($selector);
      if( $node->nextSibling )
      {
         $node->parentNode->insertBefore($this->_content, $node->nextSibling);
      }
      else
      {
         $node->parentNode->appendChild($this->_content);
      }
   }
   public function appendTo($selector)
   {
      $node = $this->_getElement($selector);
      $node->appendChild($this->_content);
   }
   public function prependTo($selector)
   {
      $node = $this->_getElement($selector);
      $node->insertBefore($this->_content);
   }
   protected function _getElement($selector)
   {
      if ( substr($selector, 0, 1) == '#' )
      {
         $elem = $this->_document->getElementById(substr($selector, 1));
         if ( is_null($elem) )
            throw new \Exception('No element found in document with that ID');
         return $elem;
      }
      $XPath = new \DOMXPath($this->_document);
      $pos   = strpos($selector, '[');
      if ( $pos !== false )
      {
         $index = (int)substr($selector, $pos+1, strpos($selector, ']')-1);
         $selector = substr($selector, 0, $pos);
      }
      else
      {
         $index = 0;
      }
      $query    = $this->_parse_selector($selector);
      $nodeList = $XPath->query($query);
      if ( $nodeList->length < $index )
         throw new \Exception('XPath query did not return '. number_format($index, 0) .' or more NodeList in TemplateFragment::_getElement(".classname")');
      return $nodeList->item($index);
   }
   protected function _parse_selector($selector)
   {
      preg_match('~([^#|^.]?)([\.?|#?])(.+)~', $selector, $matches);
      $query  = '//';
      $query .= !empty($matches[1]) ? $matches[1] : '*';
      if ( isset($matches[2]) )
      {
         $query .= str_replace(array('.', '#'), array("[@class='", "[@id='"), $matches[2]);
         if ( isset($matches[3]) ) $query .= $matches[3] ."']";
      }
      return $query;
   }
}

index.php


<?php
include 'phantom/classes/templating/Template.class.php';
include 'phantom/classes/templating/TemplateFragment.class.php';


use \phantom\classes\templating as tmpl;
try
{
   $page = new tmpl\Template('default');
   // this works fine as id="header" is in the default template
   $page->getFragment('default/slider')->insertAfter('#header');
   $page->getFragment('b2c/navigation')->insertAfter('#header');
   // this doesn't work as main_nav is in the slider template
   $page->getFragment('b2c/navigation')->insertAfter('#header');
   $page->getFragment('default/slider')->insertAfter('#main_nav');
   echo $page->getContents();
}
catch ( Exception $e )
{
   echo $e->getMessage();
}

 

 

Thanks for any help.

Link to comment
Share on other sites

Managed it, but for some reason setting preserveWhitespace to false isn't working properly.

 

 

I had to do it a bit of a dirty way, reloading the html every time a node is inserted, still could do with a better way.

 

 

 

Template.class.php


<?php
namespace phantom\classes\templating;
class Template {
   protected $_document;
   protected $_settings = array(
      'version'             => '4.01',
      'encoding'            => 'UTF-8',
      'template_dir'        => 'templates',
      'template_ext'        => 'tmpl.php',
      'preserve_whitespace' => 0
   );
   
   public function __construct($tmpl_file, array $data = array(), array $settings = array())
   {
      $this->_settings = array_merge($this->_settings, $settings);
      $this->_document = new \DOMDocument($this->_settings['version'], $this->_settings['encoding']);
      $this->_document->preserveWhiteSpace = $this->_settings['preserve_whitespace'];
      $this->_document->loadHTML($this->_getContent($tmpl_file, $data));
   }
   public function getFragment($file_name, array $data = array())
   {
      return new TemplateFragment($this->_getContent($file_name, $data), $this->_document);
   }
   public function getContents()
   {
      return $this->_document->saveHTML();
   }
   protected function _getContent($file_name, array $data = array())
   {
      ob_start();
      extract($data, EXTR_SKIP);
      include $this->_settings['template_dir'] . DIRECTORY_SEPARATOR . $file_name .'.'. $this->_settings['template_ext'];
      return ob_get_clean();
   }
}

 

 

TemplateFragment.class.php


<?php
namespace phantom\classes\templating;
class TemplateFragment {
   protected $_content;
   protected $_document;
   
   public function __construct($content, \DOMDocument $document)
   {
      $this->_document = $document;
      $this->_content  = $this->_document->createDocumentFragment();
      $this->_content->preserveWhitespace = false;
      $this->_content->appendXML($content);
   }
   public function appendTo($selector)
   {
      $this->_insertNode($selector, false, true);
   }
   public function prependTo($selector)
   {
      $this->_insertNode($selector, true, true);
   }
   public function insertBefore($selector)
   {
      $this->_insertNode($selector, true, false);
   }
   public function insertAfter($selector)
   {
      $this->_insertNode($selector, false, false);
   }
   protected function _insertNode($selector, $top, $inside)
   {
      $node = $this->_getElement($selector);
      if ( $inside && $top )
      {
         $node = $node->insertBefore($this->_content, $node->firstChild);
      }
      elseif ( !$inside && $top )
      {
         $node = $node->parentNode->insertBefore($this->_content, $node);
      }
      elseif ( $inside && !$top )
      {
         $node = $node->appendChild($this->_content);
      }
      elseif ( !$inside && !$top )
      {
         if( $node->nextSibling )
         {
            $node = $node->parentNode->insertBefore($this->_content, $node->nextSibling);
         }
         else
         {
            $node = $node->parentNode->appendChild($this->_content);
         }
      }
      $this->_document->loadHTML($this->_document->saveHTML());
   }
   protected function _getElement($selector)
   {
      if ( substr($selector, 0, 1) == '#' )
      {
         $elem = $this->_document->getElementById(substr($selector, 1));
         if ( is_null($elem) )
            throw new \Exception('No element found in document with that ID');
         return $elem;
      }
      $XPath = new \DOMXPath($this->_document);
      $pos   = strpos($selector, '[');
      if ( $pos !== false )
      {
         $index = (int)substr($selector, $pos+1, strpos($selector, ']')-1);
         $selector = substr($selector, 0, $pos);
      }
      else
      {
         $index = 0;
      }
      $query    = $this->_parse_selector($selector);
      $nodeList = $XPath->query($query);
      if ( $nodeList->length < $index )
         throw new \Exception('XPath query did not return '. number_format($index, 0) .' or more NodeList in TemplateFragment::_getElement(".classname")');
      return $nodeList->item($index);
   }
   protected function _parse_selector($selector)
   {
      preg_match('~([^#|^.]?)([\.?|#?])(.+)~', $selector, $matches);
      $query  = '//';
      $query .= !empty($matches[1]) ? $matches[1] : '*';
      if ( isset($matches[2]) )
      {
         $query .= str_replace(array('.', '#'), array("[@class='", "[@id='"), $matches[2]);
         if ( isset($matches[3]) ) $query .= $matches[3] ."']";
      }
      return $query;
   }
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.