SA__
SA__

Reputation: 447

Getting all elements between html tag in php

I refered this question

But, i want to iterate and get all the elements between the html tag

This is what i did

$homepage = file_get_contents('http://www.example.com');

Which will print the following

<html>
<body>
<div class = "alpha">hey</div>
<div class = "beta">one</div>
<div class = "beta">two</div>
</body>
</html>

Here i need to get all the elements with the class beta.

How can i do this ?

Here's the code that i tried so far

$dom = new DOMDocument();
$dom->loadHTML($homepage);
foreach($dom->getAllElements as $element ){
    if(!$element->hasClass('beta')){
       echo $element;
    } 
}

But it says DOMDocument::loadHTML(): Tag nav invalid in Entity,

Upvotes: 2

Views: 356

Answers (1)

Mani7TAM
Mani7TAM

Reputation: 469

Try this

<?php

$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML("<html>
<body>
<div class = 'alpha'>hey</div>
<div class = 'beta'>one</div>
<div class = 'beta'>two</div>
</body>
</html>");
libxml_clear_errors();

$classname="beta";
$finder = new DomXPath($dom);
$spaner = $finder->query("//*[contains(@class, '$classname')]");

foreach($spaner as $element ){
 print_r($element);
}

?>

Upvotes: 4

Related Questions