How to scrape tables with DOM Crawler?
A table can be read in PHP by treating it as a structured set of rows and cells.
DOM Crawler lets you locate the table with a CSS selector, step through each row, and then step through the cells inside that row to collect their text.
Select the table, then walk rows and cells
Start with the HTML you want to parse and create a Crawler from it. Select the relevant table element, for example with a table selector, and take the first match when the page contains more than one table. From that table, filter for tr elements to get the rows. For each row, filter for td elements to get its data cells, and read the text of each cell. This nesting mirrors the structure of the table itself: table, then row, then cell.
Worked example and a quick check
The worked example uses a small table with Name, Age, and Occupation columns and two data rows. The header row uses th elements, so filtering for td inside each row naturally skips the header and returns only data cells. The resulting sequence is Yasoob, 35, Software Engineer, Pierre, 28, Product Manager. Use that pattern as a checklist: confirm the selector finds the intended table, confirm rows are found inside it, and confirm cells are found inside each row before relying on the output.
Common mix-ups to avoid
Keep the two levels separate in your own code. The outer loop handles one row at a time, while the inner loop handles one cell at a time within the current row. If a row returns no cells, check whether the row is a header row, whether the table uses a different cell element, or whether your selector matched the wrong table. If values arrive in the wrong order, check the row and cell selectors rather than flattening the whole document at once.
| Name | Age | Occupation |
|---|---|---|
| Yasoob | 35 | Software Engineer |
| Pierre | 28 | Product Manager |
Example output from the supplied worked example, in row and cell order.
Frequently asked questions
What is the basic workflow for scraping a table with DOM Crawler?
Load the HTML into a Crawler, select the table with a CSS selector, then use filter to reach its rows and each to visit each row and its cells in turn. Reading text from each cell gives you the values in row order.
What output does the worked example produce?
The example prints one cell value per line: Yasoob, 35, Software Engineer, Pierre, 28, Product Manager. That order follows the rows and cells as they appear in the table.
How do I target one table when a page has several?
Use a more specific CSS selector for the table you need, then apply the same row-and-cell iteration inside that table. Keeping the search scoped to the chosen table avoids mixing in rows from other tables on the page.