The CssSelector Component

    Note

    If you install this component outside of a Symfony application, you mustrequire the file in your code to enable the classautoloading mechanism provided by Composer. Readthis article for more details.

    This article explains how to use the CssSelector features as an independentcomponent in any PHP application. Read the article to learn about how to use it when creating Symfony tests.

    When you're parsing an HTML or an XML document, by far the most powerfulmethod is XPath.

    Many developers — particularly web developers — are more comfortableusing CSS selectors to find elements. As well as working in stylesheets,CSS selectors are used in JavaScript with the querySelectorAll() functionand in popular JavaScript libraries such as jQuery, Prototype and MooTools.

    CSS selectors are less powerful than XPath, but far easier to write, readand understand. Since they are less powerful, almost all CSS selectors canbe converted to an XPath equivalent. This XPath expression can then be usedwith other functions and classes that use XPath to find elements in adocument.

    The component's only goal is to convert CSS selectors to their XPathequivalents, using toXPath():

    This gives the following output:

    You can use this expression with, for instance, orSimpleXMLElement to find elements in a document.

    Tip

    The methoduses the CssSelector component to find elements based on a CSS selectorstring. See the The DomCrawler Component for more details.

    Not all CSS selectors can be converted to XPath equivalents.

    • link-state selectors: :link, :visited, :target
    • UI-state selectors: :invalid, :indeterminate (however, :enabled,:disabled, :checked and :unchecked are available)Pseudo-elements (:before, :after, ,:first-letter) are not supported because they select portions of textrather than elements.

    Several pseudo-classes are not yet supported:

    • :first-of-type, :last-of-type, :nth-of-type,:nth-last-of-type, :only-of-type. (These work with an elementname (e.g. li:first-of-type) but not with ).