Back to Top

To grab content from nested tags in PHP

To grab content from nested tags in PHP

Recently I am working with the scraping of data from external URL and for scraping we always need to use a preg_match function to get matched data.

I want to fetch all “div” tags and their respective content and nested div’s through PHP function and I have used preg_match, but it’s creating an issue.
For example, I have syntax for HTML tags something like below

contents

In from above code, I want to get everything within the div class=’xyz’ but preg_match function going to stop executing after getting the first tag.

So, I have used DOMDocumen for fetching all nested divs value within div class=’xyz’ using the nodeValue element of DOMDocument but it is not returning HTML tags within the div tag.

Here, I am going to explain how I solve above issue when try to fetch multiple nested divs in PHP so let’s see the code.

function nestedHTML($node)
{
    $doc  = $node->ownerDocument;
    $frag = $doc->createDocumentFragment();
    foreach ($node->childNodes as $child)
    {
        $frag->appendChild($child->cloneNode(TRUE));
    }
    return $doc->saveXML($frag);
} 

$html = "
contents
"; libxml_use_internal_errors(true); // if any warning generate $doc = new DOMDocument(); $doc->loadHTML($html); $doc->saveHTML(); $nodes = $doc->getElementsByTagName('div'); foreach ($nodes as $node) { $class = $node->getAttribute('class'); if($class == 'xyz'){ echo nestedHTML($node); } }

That’s it. you just need to change URL or code require to display.

Thank you for reading.Feel free to share your thoughts! Don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates.

Comments (1)

  1. Nice Tutorial…keep up the good work
    Thanks For Sharing….i m gonna try this

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Most Popular Posts

How to check user is logged in Modx

Posted on 6 years ago

Bhumi

How to use WebService in PHP

Posted on 4 years ago

Bhumi

Getting started with Laravel

Posted on 1 year ago

Bhumi

An Introduction to Gulp JS

Posted on 1 year ago

Bhumi

The Reader’s Poll – June 2015

Posted on 3 years ago

Bhumi

The Reader’s Poll – August 2014

Posted on 4 years ago

Bhumi

The Reader’s Poll – June 2014

Posted on 4 years ago

Bhumi

The Readers’ Poll – May 2014

Posted on 5 years ago

Bhumi

The Readers’ Poll – August 2013

Posted on 5 years ago

Bhumi