PHP DOM Element failing to handle HTML tag like strong, anchor, div etc

We have exactly the same problem as this.

I have used this code in my project and it is working fine but the problem is that I want to load all HTML tags which are available in that div tag like a strong, anchor, div, etc. but I don’t know how to do that.

we have used below code:

<?php while (have_posts()) : the_post();

ob_start(); // run the_content() through the Output Buffer
the_content();
$html = ob_get_clean(); // Store the formatted HTML
$content = new DomDocument(); // Create a new DOMDocument Object to work with our HTML
$content->loadHTML(‘<meta http-equiv=”content-type” content=”text/html; charset=utf-8″>’. $html );
$finder = new DomXPath( $content ); // Create a new DOMXPath object with our $content object that we will evaluate
$classname = ‘TEST’; // The class we are looking for

$item_list = $finder->query(“//*[contains(@class, ‘$classname’)]”); // Evaluates our content and will return an object containing the number of items matching our query
?>
<div id = “result”>`
<?php
// echo the value of each item found
// You might want to format or wrap your $value according to your specification if necessary
for( $i = 0; $i < $item_list->length; $i++ ){
$value = $item_list->item( $i )->nodeValue;

echo $value; //die();
?>

<?php

// if you want the text to be a link to the post, you could use this instead
// echo ‘<a href=”‘ . get_the_permalink() . ‘”>’ . $value . ‘</a>’;

}
?>
</div>

which gives output like below:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

but we want output like below

<h2>Lorem ipsum dolor sit amet</h2>

<a href=”https://google.com”>Lorem ipsum dolor sit amet</a>, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea <strong>commodo consequat</strong>. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Can anybody help me in this?

Read more here:: PHP DOM Element failing to handle HTML tag like strong, anchor, div etc

Leave a Reply

Your email address will not be published. Required fields are marked *