Reputation: 55
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
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";
}
Upvotes: 3
Reputation: 6500
This is a jQuery solution, not PHP:
$('.section1).each(function() {
return $(this).html();
});
Upvotes: 1