Skip to content

Getting Started: 1. Your First XML Document

Daniele Orlando edited this page Dec 17, 2020 · 4 revisions

First of all, depending the method you have chosen to install FluidXML, you have two options to include the library.

  • If you have cloned the repository, copy the source/FluidXml* files in your PHP project and include it:
require_once 'FluidXml.php';
  • If you have installed the library using Composer, include the autoloader:
require_once 'vendor/autoload.php';

Now use classes and functions you need.

Concise syntax

use function \FluidXml\fluidxml;
use function \FluidXml\fluidns;
use function \FluidXml\fluidify;

Extended syntax

use \FluidXml\FluidXml;
use \FluidXml\FluidNamespace;

We can proceed to create our first XML document in the simplest way.

Concise syntax

$book = fluidxml();

Extended syntax

$book = new FluidXml();

It creates a new XML document with one root node by default called <doc/>.

echo $book;
<?xml version="1.0" encoding="UTF-8"?>
<doc/>

Whether there is the need to influence the document creation, the constructor supports some options.

Concise syntax

$book = fluidxml('book', ['stylesheet' => 'http://domain.com/style.xsl']);

// Which is the same of

$book = fluidxml(null, ['root' => 'book', 'stylesheet' => 'http://domain.com/style.xsl']);

Extended syntax

$book = new FluidXml('book', ['stylesheet' => 'http://domain.com/style.xsl']);

// Which is the same of

$book = new FluidXml(null, ['root' => 'book', 'stylesheet' => 'http://domain.com/style.xsl']);

Our XML document now has a root node called <book/>.

Pro Tip:
Supported options:

[ 'root'       => 'doc',    // The root node of the document.
  'version'    => '1.0',    // The version for the XML header.
  'encoding'   => 'UTF-8',  // The encoding for the XML header.
  'stylesheet' => null ]    // An url pointing to an XSL file.

Pro Tip:
The Ruby object construction style is supported too with PHP 7.

$doc = FluidXml::new('book', [/* options */]);

2. Adding Nodes 〉