Skip to content
Thomas Weinert edited this page Jul 12, 2018 · 2 revisions

Create XML

FluentDOM has two main ways to create a DOM document. One uses a function syntax, the other extended DOM methods. They can be mixed of course.

Function Syntax (Creator)

The function syntax is based on an object that implements the magic method __invoke and a fluent API.

First you have to get an new Creator object and register namespaces.

$_ = FluentDOM::create();
$_->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
$_->formatOutput = TRUE;

$_ is a nice, short name, but you can use any other variable name (for example $create).

Next are nested calls to the function. The first argument is always the element name. The other arguments are appended as attributes (an array), text nodes (a scalar) or nodes (objects that extend DOMNode or implement FluentDOM\Appendable).

echo $_(
  'atom:feed',
  $_('atom:title', 'Example Feed'),
  $_('atom:link', ['href' => 'http://example.org/']),
  $_('atom:updated', '2003-12-13T18:30:02Z'),
  $_(
    'atom:author',
    $_('atom:name', 'John Doe')
  ),
  $_('atom:id', 'urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6'),
  $_(
    'atom:entry',
    $_('atom:title', 'Atom-Powered Robots Run Amok'),
    $_('atom:link', ['href' => 'http://example.org/2003/12/13/atom03']),
    $_('atom:id', 'urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a'),
    $_('atom:updated', '2003-12-13T18:30:02Z'),
    $_('atom:summary', 'Some text.')
  )
);

The return value of the function is an object that implements FluentDOM\Appendable. That is how the calls can be nested. It implements __toString() so that you can just echo it.

DOM Syntax

The other way is using the DOM methods.

$document = new FluentDOM\DOM\Document();
$document->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
$document->formatOutput = TRUE;

$feed = $document->appendElement('atom:feed');
$feed->appendElement('atom:title', 'Example Feed');
$feed->appendElement('atom:link', ['href' => 'http://example.org/']);
$feed->appendElement('atom:updated', '2003-12-13T18:30:02Z');
$author = $feed->appendElement('atom:author');
$author->appendElement('atom:name', 'John Doe');
$feed->appendElement('atom:id', 'urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6');
$entry = $feed->appendElement('atom:entry');
$entry->appendElement('atom:title', 'Atom-Powered Robots Run Amok');
$entry->appendElement('atom:link', ['href' => 'http://example.org/2003/12/13/atom03']);
$entry->appendElement('atom:id', 'urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a');
$entry->appendElement('atom:updated', '2003-12-13T18:30:02Z');
$entry->appendElement('atom:summary', 'Some text.');

echo $document->saveXml();

appendElement() combines FluentDOM\DOM\Document::createElement() and DOMNode::appendChild(), You can call them separately and FluentDOM\DOM\Document::createElement() will use the registered namespaces to resolve prefixes.

Clone this wiki locally