user1105971
user1105971

Reputation: 55

For each div tag, take its contents

I'm trying to loop through the code of a HTML page and reformat it's contents. It has a few div's within div's, which I want to extract. I've tried various forms of explode, regex and DOM, but can't find exactly how to do this.

Example:

<div class="section1">
 <div class="section2">number 1</div>
</div>
<div class="section1">
 <div class="section2">number 2</div>
</div>

The result I'm looking for is basically, for each section 1, get contents from section 2, so the output would be: number 1, number 2

Does anyone know how to do something like this?

Upvotes: 1

Views: 155

Answers (2)

Jon
Jon

Reputation: 437336

Should be pretty easy with DOMXPath:

$doc = new DOMDocument;
$doc->loadHTML(/*...*/); // load the HTML here
$xpath = new DOMXPath($doc);
$result = $xpath->query("//div[@class='section1']/div[@class='section2']/text()");

foreach ($result as $item) {
    echo "$item->wholeText\n";
}

See it in action.

Upvotes: 3

Andrea Turri
Andrea Turri

Reputation: 6500

This is a jQuery solution, not PHP:

$('.section1).each(function() {
    return $(this).html();
});

Upvotes: 1

Related Questions