Accessing HTML DOM Elements with PHP

Date Posted: January 6, 2015, 4:05 am


extract-url-contents

Demo Download Demo

 

Tutorial

Download Library

Include the Library

1
include_once("include/simple_html_dom.inc.php");

Get URL Content:

1
2
3
$get_url = 'http://carlofontanos.com';
$get_content = file_get_html($get_url);
print_r($get_content);

Get Page Title:

1
2
3
4
5
$get_content = file_get_html($get_url);
foreach($get_content->find('title') as $element) {
    $page_title = $element->plaintext;
    print_r($page_title);
}

Get Body Text

1
2
3
4
5
6
7
$get_content = file_get_html($get_url);
foreach($get_content->find('body') as $element) {
    $page_body = trim($element->plaintext);
    $pos = strpos($page_body, ' ', 200); //Find the numeric position to substract
    $page_body = substr($page_body,0,$pos ); //shorten text to 200 chars
    print_r($page_body . '<br />');
}

Get all images in the content:

1
2
3
4
5
6
$image_urls = array();
foreach($get_content->find('img') as $element) {
    if($element->src){
        echo '<img src ="' . $element->src . '" width = "100" height = "100" />';
    }  
}

About author


Carl Victor Fontanos

A fine gentleman specializing in front-end and back-end development with extensive experience building high performance web applications that keeps users engaged and help businesses grow.

 
Hire Me