Search code examples
phpincludesimple-html-dom

Two Instances of Simple HTML Dom


I am currently using php include to source two files onto a web page.

The two different files say 1.php and 2.php have two different instances using simplehtmldom.

The issue is with 2.php when included onto the web page, shows the following error in its position.

Fatal error: Cannot redeclare file_get_html() (previously declared in /home/northsho/public_html/w/pages/simple_html_dom.php:70) in /home/northsho/public_html/w/pages/simple_html_dom.php on line 85

edit:

further clarification.

master.php (includes 1.php and 2.php)

1.php and 2.php both use simple_html_dom.php


Solution

  • use this structure, although you could do without including those 2 files and moving the contents into a function and passing the URL as a parameter

    master.php

    <?php
    include 'simple_html_dom.php';
    
    include '1.php';
    include '2.php';
    

    1.php

    <?php
    $html = file_get_html('http://example.domain.com');
    
    //do your job
    
    //destroy the object at the end
    $html->clear(); 
    unset($html);
    

    2.php

    <?php
    $html = file_get_html('http://anotherexample.domain.com');
    
    //do your job
    
    //destroy the object at the end
    $html->clear(); 
    unset($html);
    

    master.php using a function instead of including 2 other files

    <?php
    include 'simple_html_dom.php';
    
    function doMyJob($url){
        $html = file_get_html($url);
    
        //do the actual job
        $result = $html->plaintext;
    
        $html->clear();
        unset($html);
    
        return $result;
    }
    
    //call the function
    print doMyJob("http://example.com");