FluentDOM\Document::createElement PHP Method

createElement() public method

Allow to add a text content and attributes directly. If $content is an array, the $content argument will be merged with the $attributes argument.
public createElement ( string $name, string | array $content = NULL, array $attributes = NULL ) : Element
$name string
$content string | array
$attributes array
return Element
    public function createElement($name, $content = NULL, array $attributes = NULL)
    {
        list($prefix, $localName) = QualifiedName::split($name);
        $namespace = '';
        if ($prefix !== FALSE) {
            if (empty($prefix)) {
                $name = $localName;
            } else {
                if (isset($this->_reserved[$prefix])) {
                    throw new \LogicException(sprintf('Can not use reserved namespace prefix "%s" in element name.', $prefix));
                }
                $namespace = $this->getNamespace($prefix);
            }
        } else {
            $namespace = $this->getNamespace('#default');
        }
        if ($namespace != '') {
            $node = $this->createElementNS($namespace, $name);
        } elseif (isset($this->_namespaces['#default'])) {
            $node = $this->createElementNS('', $name);
        } else {
            $node = parent::createElement($name);
        }
        $this->appendAttributes($node, $content, $attributes);
        $this->appendContent($node, $content);
        return $node;
    }

Usage Example

Example #1
0
 /**
  * Create an Element node and configure it.
  *
  * The first argument is the node name. All other arguments are flexible.
  *
  * - Arrays are set as attributes
  * - Attribute and Namespace nodes are set as attributes
  * - Nodes are appended as child nodes
  * - FluentDOM\Appendable instances are appended
  * - Strings or objects castable to string are appended as text nodes
  *
  * @param string $name
  * @param mixed ...$parameters
  * @return \FluentDOM\Element
  */
 public function element($name, ...$parameters)
 {
     $node = $this->_document->createElement($name);
     foreach ($parameters as $parameter) {
         $node->append($parameter);
     }
     return $node;
 }