$fluid = fluidify($simplexml); echo $fluid->xml(); echo "————————————————————————————————————————————————————————————————————————————————\n"; // XML file import. // $fluid = fluidify('path/to/file.xml'); /****************** * XPath Queries. * *******************/ /* * XPath queries can be absolute or relative to the context over they are executed. */ $eggs = $food->query('//egg'); $fruits = $food->query('//fruit[@price="expensive"]'); echo "We have {$eggs->length()} eggs and {$fruits->length()} expensive fruit.\n"; echo "————————————————————————————————————————————————————————————————————————————————\n"; $book->query('//chapter')->attr('lang', 'en')->query('..')->attr('lang', 'en')->query('../title')->attr('lang', 'en'); /* * The previous code presents a repetition: all 'setAttribute' calls are identical. * It can be refactored taking advantage of an advanced feature of 'query'. */ $book->query('//chapter', '//chapters', '/book/title')->attr('lang', 'en'); /******************************* * Accessing The Node Content. * ********************************/ /* * The result of a query can be accessed even as array. * Accessing the result of a query as array performs the unwrapping of the node * and returns a raw instance of DOMNode. * You loose the FluidXML interface but gain direct access to the DOMNode apis. */ $chapters = $book->query('//chapter');
describe('.asArray', function () { it('should return an array of nodes inside the context', function () { $xml = new FluidXml(); $cx = $xml->appendChild(['head', 'body'], true); $a = $cx->asArray(); $actual = $a; assert(\is_array($actual)); $actual = \count($a); $expected = 2; assert($actual === $expected, __($actual, $expected)); }); }); describe('.length', function () { it('should return the number of nodes inside the context', function () { $xml = new FluidXml(); $cx = $xml->query('/*'); $actual = $cx->length(); $expected = 1; assert($actual === $expected, __($actual, $expected)); $cx = $xml->appendChild(['child1', 'child2'], true); $actual = $cx->length(); $expected = 2; assert($actual === $expected, __($actual, $expected)); $cx = $cx->appendChild(['subchild1', 'subchild2', 'subchild3']); $actual = $cx->length(); $expected = 2; assert($actual === $expected, __($actual, $expected)); $cx = $cx->appendChild(['subchild4', 'subchild5', 'subchild6', 'subchild7'], true); $actual = $cx->length(); $expected = 8; assert($actual === $expected, __($actual, $expected));