Question

I'm completely stuck on this issue! I'm using the php-simple-html-dom-parser and this is loaded with PSR-0. I'm not that familiar with PSR-0. But I use the class just as the readme file shows but I can't get it working.

In my IDE, autcompletion is working fine and not any error is shown. But when I run the script, I get this error:

Fatal error: Class 'Sunra\PhpSimple\HtmlDomParser' not found in C:\xampp\htdocs\folder\test.php on line 3

Code:

<?php
use Sunra\PhpSimple\HtmlDomParser;
$dom = HtmlDomParser::file_get_html();

File structure:

folder\
  Sunra\
    PhpSimple\
      simplehtmldom_1_5\
      HtmlDomParser.php
test.php

As I said, I really have no idea what is going wrong. So probably I'm looking for the wrong thing and that's why I post this question.

Was it helpful?

Solution

Download Composer

In your project directory run:

php composer.phar require sunra/php-simple-html-dom-parser ~1.5

In your php file (index.php for example), add:

<?php

include 'vendor/autoload.php';

use Sunra\PhpSimple\HtmlDomParser;

$dom = HtmlDomParser::file_get_html();

Here, when you include vendor/autoload.php the composer generated autoloading configuration handles all class autoloads for you. Nearly all libraries on github that follow PSR-0 exist on Packagist making them available for install in this way.

You may want to read up on Semantic Versioning to get an idea of what you are installing when you require libraries.

Most modern PHP frameworks now use Composer for their dependencies. However it is still fully feasible for small projects of even a single file.

OTHER TIPS

Well, you aren't using an autoloader, so the class will not be loaded automatically.

Here's a minimal autoloader example that uses PSR-0.


After you understand Autoloading, you should try and use dependency management frameworks like Composer. See Flosculus's answer for more details.

Using the PSR-0 autoloader, did you add it to a spl_autoload_register('autoload'), or are you using composer and included composers autoloader?

This works for me:

<?php
function autoload($className)
{
    $className = ltrim($className, '\\');
    $fileName  = '';
    $namespace = '';
    if ($lastNsPos = strrpos($className, '\\')) {
        $namespace = substr($className, 0, $lastNsPos);
        $className = substr($className, $lastNsPos + 1);
        $fileName  = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
    }
    $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';

    require $fileName;
}
spl_autoload_register('autoload');

use Sunra\PhpSimple\HtmlDomParser;

$dom = HtmlDomParser::file_get_html('http://google.com');
var_dump($dom);
?>

Source: http://www.php-fig.org/psr/psr-0/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top