Get the text from all elements with a nominated class as a flat array

Get the text from all elements with a nominated class as a flat array

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Extracting Structured Text from HTML into Parallel Arrays

You often encounter HTML structures where content is nested within specific wrapper classes. In your scenario, you have paragraphs containing a heading span followed by a content span. You want to flatten this structure into two parallel arrays: one for the headings and another for the corresponding body text.

While jQuery provides a concise syntax for traversing DOM elements, relying on it solely for data extraction can sometimes obscure the underlying mechanics of how the browser represents the document. If you are working within a PHP environment where jQuery is not available or desirable, the DOMDocument class offers a robust alternative that keeps your dependencies low and your logic explicit.

The DOM Approach in Pure PHP

The core challenge here is mapping elements from one parent (p) to their children while ignoring intermediate wrappers. If you simply iterate over all span elements, you lose the context of which heading belongs to which line of text. You need to group these items by their common ancestor.

Using the DOM extension, you can select all p elements first, then drill down into each one. This ensures you maintain the structural relationship between the header and the content. Here is a practical implementation:

$dom = new DomDocument();
@$dom->loadHTML($html); // Suppress warnings for malformed HTML if necessary
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;

$headings = [];
$contents = [];

// Select all paragraph elements directly
$paragraphs = $dom->getElementsByTagName('p');

foreach ($paragraphs as $p) {
    // Retrieve the heading span
    $headingSpan = $p->getElementsByClassName('Heading1-H')->item(0);
    
    // Retrieve the content span
    $contentSpan = $p->getElementsByClassName('Normal-H')->item(0);

    if ($headingSpan && $contentSpan) {
        // Extract text, trimming whitespace to clean up newlines or spaces
        $headings[] = trim($headingSpan->nodeValue);
        $contents[] = trim($contentSpan->nodeValue);
    }
}

In this example, getElementsByTagName('p') acts as your anchor. By checking for the existence of both the .Heading1-H and .Normal-H spans before adding data to your arrays, you prevent misalignment if a paragraph is malformed or missing a component. The use of trim() is critical here; raw node values often include newline characters that make string comparison or downstream processing difficult.

Performance and Trade-offs

When deciding between jQuery and native DOM methods in PHP, the primary differentiator is often overhead versus readability. jQuery executes in the browser's context, whereas this approach runs on the server. If you are building a backend parser, sticking to the DOMDocument extension avoids loading external scripts just to process HTML strings.

One pitfall to watch out for is the strictness of class matching. The code above assumes exactly one heading and one content element per paragraph. If your HTML source allows multiple headings or mixed ordering (e.g., content before the title), a simple item(0) lookup might return the wrong element or fail entirely.

For more complex scenarios where you need to handle unordered siblings, XPath offers a more powerful filtering mechanism directly within PHP:

// Using XPath for flexible queries
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//p[.//span[@class="Heading1-H"] and .//span[@class="Normal-H"]]');

foreach ($nodes as $node) {
    $headings[] = trim($xpath->evaluate('string(//span[@class="Heading1-H"])', $node));
    $contents[] = trim($xpath->evaluate('string(//span[@class="Normal-H"])', $node));
}

This approach queries the entire document tree to find paragraphs that contain both required classes, regardless of their order in the DOM. It is more resilient but slightly more verbose than direct element traversal.

When to Use Laravel Collections

If you are already working within a Laravel application, this parsing logic can be encapsulated elegantly using Eloquent or native collections once the raw data is fetched. However, if you are processing a large stream of HTML without an active request cycle or database connection, keeping the parsing logic in pure PHP with DOMDocument remains the most efficient strategy. It keeps your application lightweight and ensures that your text extraction logic is independent of framework bootstrapping times.

Our network