Jeenal Infotech

How to get HTML element in PHP

Sometime we need to parse an HTML document in PHP. First thing come in ones mind is regular expression, since they are good to finding the pattern in string. Nevertheless, the reality is that HTML document can be little difficult so finding the pattern in HTML document will be difficult too.

But don’t worry we have good news 🙂 – there is already a PHP library that is made for parsing HTML.


//Download below php library file from https://sourceforge.net/projects/simplehtmldom/?source=typ_redirect

// Import Library
include_once('simple_html_dom.php');

// Create DOM from URL or file
$html = file_get_html('http://www.jeenalinfotech.com/');

// Find all videos
foreach($html->find('video') as $element)
echo $element->src . '';

// Find all images
foreach($html->find('img') as $element)
echo $element->src . '';

// Find all links
foreach($html->find('a') as $element)
echo $element->href . '';

Output:

//Didn't find <video> tag on this page 

//<img> tag result
http://www.jeenalinfotech.com/wp-content/uploads/2016/02/cropped-desktop-hd-apple-black-background.jpg

//<a> tag result
https://www.facebook.com/MilanPantech
https://twitter.com/milan_panchal24

Leave a Reply

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

Show Buttons
Hide Buttons