Skip to content

Find HTML elements by multiple tags with DOM Crawler

When a page uses different tags for the same kind of content, a single tag selector will miss part of the result.

OUTPUT FORMATSHTMLJSONMarkdown

Combining tag names in one CSS selector lets DOM Crawler return all matching elements together, in document order, so you can process them in one pass.

How the multi-tag selector works

Pass the filter method a CSS selector listing each tag name, separated by commas. For example, h1, h2 asks for every level-one and level-two heading on the page. The comma means 'or': an element is included when it matches any one of the listed tags. This differs from writing tags next to each other without a comma, which would describe a nested relationship rather than a choice between tags.

A practical workflow has four steps. First, fetch the page HTML with an HTTP client such as Guzzle. Second, load that HTML into a DOM Crawler instance. Third, call filter() with the comma-separated selector. Fourth, iterate over the returned nodes and read textContent from each one. Keeping the selection and the text extraction separate makes it easy to change the tag list later without rewriting the loop.

Worked example: collecting h1 and h2 text

The protected example below fetches a homepage, selects h1 and h2 elements together, and prints their text. The printed lines show why grouping helps: marketing headings and later section headings appear in one combined list, even though they use different tags. If only h1 were selected, the h2 lines would be lost; if only h2 were selected, the main heading would be lost.

Use this pattern as a checklist when adapting it: confirm the HTTP response body is a string before creating the crawler, confirm every tag in the selector is spelled as it appears in the markup, and check the loop output against the visible page so missing or duplicated headings are spotted early.

Adapting the selector

Extend the same idea by adding more tag names to the comma-separated list, or by combining a tag with a class or attribute in the selector when only some elements of those tags are wanted. Keep the list short and purposeful: each extra tag widens the result set, so verify the output after every change. For related tasks, see the linked questions on XPath selectors, finding links, selecting by attribute or class, sibling nodes, tables, and values between two nodes.