Sherin Jose
Sherin Jose

Reputation: 2526

SimpleHtmlDom extract content inside a div not from its child

I want to extract content from a div, but not needed the contents from its childrens. I m using simplehtmldom parser and the following code

//html code
<div id="frame">
Needed this content
<a href="#">Not needed</a>
</div>

//php code
$elem     =  file_get_html($url);
$content  =  $elem->find('div#frame')->plaintext;
echo $content;

but this code results,

Needed this contentNot needed

I want the result as,

Needed this content

How to change th code for getting that output. Help plz. thanks in advance

Upvotes: 2

Views: 1618

Answers (1)

Enissay
Enissay

Reputation: 4953

The only way I can think of, is to delete all your div's children, then print the left content... Here's how:

// includes Simple HTML DOM Parser
include "simple_html_dom.php";

$text = '<div id="frame">
<span><b>Not needed</b></span>
Needed this content
<a href="#">Not needed</a>
</div>';

//Create a DOM object
$html = new simple_html_dom();
// Load HTML from a string
$html->load($text);

$content = $html->find('div#frame',0);  

// Before
echo $content->innertext;

// Delete all unwanted children
foreach( $content->children() as $i => $unwantedTags ) {

    echo "<br/>$i => ".$unwantedTags->tag;

    $unwantedTags->outertext = '';
}

// After
echo "<br/>".$content->innertext;

// Clear dom object
$html->clear(); 
unset($html);

See this working DEMO

Upvotes: 1

Related Questions