-
Notifications
You must be signed in to change notification settings - Fork 20
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.
FluentDOM::load() returns an extended DOM document.
$element = simplexml_load_string($string);
echo $element->saveXML();$element = simplexml_load_file($file);
echo $element->saveXML();$document = FluentDOM::load($string);
echo $document->saveXML();$document = FluentDOM::load($file, 'xml', [FluentDOM\Loader\Options::IS_FILE => TRUE]);
echo $document->saveXML();$document = FluentDOM::load('<div/>', 'html');
echo $document->saveHTML();$document = FluentDOM::load('{"foo": "bar"}', 'json');
echo $document->saveXML();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";A problem with the object syntax is that it can result in error messages if an expected node structure does not exists.
$element = simplexml_load_string('<foo/>');
var_dump($element->some->other->element);
// PHP Notice: Trying to get property of non-object inUsing Xpath avoids the problem. If the location path returns and empty list, the result of the string cast will be an empty string.
$document = FluentDOM::load('<foo/>');
var_dump($document('string(/root/some/other/element)'));
// string(0) ""You can use Xpath to validate if a node exists of course.
$document = FluentDOM::load('<foo/>');
var_dump($document('count(/root/some/other/element) > 0'));
// bool(false)- Home
- Getting Started
- Tasks
- Plugins
- Functions
- Lists
- Creator (5.1)
- CSS Selectors
- Convertors
- Loaders
- Serializers (5.1)
- Transformers (5.1)
- Extended DOM
- XMLReader (6.1)
- XMLWriter (6.1)
- Interfaces