Skip to content

Extracting Data in PHP with CSS Selector Rules

When you only need particular fields from a page, you can describe those fields with CSS selectors and let the API return them directly.

OUTPUT FORMATSHTMLJSONMarkdown

In PHP, that means building a small label-to-selector map, encoding it as JSON, and sending it with the target URL and your API key.

Why send selectors with the request

Instead of downloading a page and searching its markup locally, you name each wanted field and give the selector that finds it. The service applies those selectors during the request and returns the matched values in a structured form. This is useful when the fields are stable and known in advance, such as a heading or a subtitle, because the PHP code stays focused on the request and the response.

Worked example: a title and a subtitle

Start with the page you intend to scrape and identify the elements in the browser. For the worked example, the page title is matched by h1 and the subtitle by span.text-[20px]. Those two entries become a map from the labels title and subtitle to their selectors. Before relying on a selector, test it in the browser console with document.querySelector and confirm that it selects the intended element rather than a similar one elsewhere on the page.

Complete PHP request

The complete PHP implementation is provided as protected module code0001. It uses cURL to send a GET request, builds the query string from the API key, target URL, and encoded extract_rules, then prints the HTTP status code and response body. If the request fails, it stops and reports the cURL error and error code. Review the module for the exact field names, endpoint construction, and error handling before adapting it.

Pre-flight checklist

Use this checklist before running the example: confirm each selector in the browser console; confirm the target URL is the page you tested; replace the API key placeholder with your own key; encode the label-to-selector map as JSON; and inspect both the HTTP status code and the response body after the request. If a field is missing, retest its selector first, because a selector that matches the wrong element or no element will produce the wrong result even when the request succeeds.

Frequently asked questions

Do I need to parse the HTML myself after requesting extracted fields?

No. The API returns the values matched by your selectors in a structured response, so you do not need a separate parsing step for those fields. You still need to check the HTTP status and handle a failed request in PHP.

How can I check a CSS selector before using it?

Open the page in a browser, open the developer tools console, and run document.querySelector with the candidate selector. If it returns the intended element, the selector is suitable for testing in your rules.