Skip to content

SimpleXML Migration

Thomas Weinert edited this page Dec 21, 2016 · 8 revisions

SimpleXML Migration

If you worked with SimpleXML before the following examples should help you to understand FluentDOM. Like SimpleXML, FluentDOM uses PHP language features and interfaces to provide an easier and more compact syntax. Unlike SimpleXML, FluentDOM tries not to hide DOM, but to extend it. PHP itself implements DOM Level 2, FluentDOM adds DOM Level 3 methods.

The complete source of the following examples can be found in the repository: /examples/SimpleXML Migration.

Load

FluentDOM::load() returns an extended DOM document.

SimpleXML load xml from string

$element = simplexml_load_string($string);
echo $element->saveXML();

SimpleXML load xml from file

$element = simplexml_load_file($file);
echo $element->saveXML();

FluentDOM load xml from string

$document = FluentDOM::load($string);
echo $document->saveXML();

FluentDOM load xml from file

$document = FluentDOM::load($file, 'xml', [FluentDOM\Loader\Options::IS_FILE => TRUE]);
echo $document->saveXML();

FluentDOM load html from string

$document = FluentDOM::load('<div/>', 'html');
echo $document->saveHTML();

FluentDOM load json from string

$document = FluentDOM::load('{"foo": "bar"}', 'json');
echo $document->saveXML();

Elements

In SimpleXML you can use object property syntax to access the tag structure. The property can be cast to string to fetch the direct text children content.

$element = simplexml_load_string($xml);
echo $element->channel->title, "\n";

FluentDOM uses Xpath to accomplish that. Nodes can be used like functions to execute an Xpath expression in the context of the node. Xpath has a string cast built in.

$document = FluentDOM::load($xml);
echo $document('string(/rss/channel/title)'), "\n";
Clone this wiki locally