Skip to content

Getting Started: 4. XPath Queries

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

The possibility to execute XPath queries easily is another feature of FluidXML.

Concise syntax

$eggs   = $food('//egg');
$fruits = $food('//fruit[@price="expensive"]');

Extended syntax

$eggs   = $food->query('//egg');
$fruits = $food->query('//fruit[@price="expensive"]');
echo "We have {$eggs->size()} eggs and {$fruits->size()} expensive fruit.\n";

Chaining queries together with the usage of relative XPath queries gives an immense flexibility.

Concise syntax

$book('//chapter')
         ->attr('lang', 'en')
     ->query('..')
         ->attr('lang', 'en')
     ->query('../title')
         ->attr('lang', 'en');

Extended syntax

$book->query('//chapter')
          ->setAttribute('lang', 'en')
     ->query('..')
          ->setAttribute('lang', 'en')
     ->query('../title')
          ->setAttribute('lang', 'en');

Note that the query ./chapter is a valid XPath query, but chapter is not; instead chapter is handled as a CSS selector and is translated to //chapter (which has a different meaning of course).

Pro Tip:
query() supports quering multiple XPaths. The previous example can be refactored
using this feature.

$book->query('//chapter', '//chapters','/book/title')
         ->attr('lang', 'en');

5. CSS Queries 〉