I-M-JM
I-M-JM

Reputation: 15950

Not able to get class loaded to PHP script

I needed HTML parser for PHP and using following library - https://github.com/paquettg/php-html-parser

I am not able to run even a simple code. Looks like something wrong is there in way I am adding files. Below is my code.

<?php
use PHPHtmlParser\Dom;

$url = 'http://google.com/';

// echo class_exists('Dom')?'yes':'no';

$dom = new Dom;
$dom->loadFromUrl($url);
$html = $dom->outerHtml;

echo $html;
?>

echo $html didn't gave me any output. So, I checked if class_exists or not, and result was no.

Am I doing anything wrong?

Upvotes: 1

Views: 1414

Answers (3)

Kaishiyoku
Kaishiyoku

Reputation: 23

I took a quick look inside the code of the Dom class and the loadFromUrl method uses the PHP core method file_get_contents to fetch the website's content. This method requires that the php.ini option allow_url_fopen is set to true.

If that is the case the issue could lie in class loading problems.

Upvotes: 0

Absalon Valdes
Absalon Valdes

Reputation: 910

If your are using composer you must include vendor/autoload.php like this

<?php

require_once __DIR__.'/vendor/autoload.php';

use PHPHtmlParser\Dom;

$url = 'http://google.com/';

// echo class_exists('Dom')?'yes':'no';

$dom = new Dom;
$dom->loadFromUrl($url);
$html = $dom->outerHtml;

echo $html;
?>

1) Download composer from https://getcomposer.org/composer.phar

2) Create a file composer.json

{
    "require": {
        "paquettg/php-html-parser": "0.1.0"
    }
}

3) Run from your terminal php composer.phar install to install dependencies

4) Now edit your script and add require_once __DIR__.'/vendor/autoload.php';

5) Learn to use composer properly https://getcomposer.org/doc/01-basic-usage.md

Upvotes: 0

Fabian Schmengler
Fabian Schmengler

Reputation: 24551

First, class_exists only works with the fully qualified class name (i.e. including namespace):

class_exists('PHPHtmlParser\Dom')

Second, you need to include an autoloader1 that tells PHP where to look for class files.

If you installed the PHPHtmlParser with composer, you can use the one generated by composer2:

require_once 'vendor/autoload.php';

If you downloaded the PHPHtmlParser source, you have to build your own autoloader or use a third party PSR-03 compatible autoloader (because this is the standard that the library uses).

Simple example:

spl_autoload_register(function($className)
    {
        $baseDir = 'PHPHtmlParser/src';
        $fileName = $baseDir . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $className) . '.php';
        if (stream_resolve_include_path($fileName)) {
            include $fileName;
            return true;
        }
        return false;
    }
);

(adjust 'PHPHtmlParser/src/ according to where you extracted the files)


1) http://php.net/autoload
2) https://getcomposer.org/doc/01-basic-usage.md#autoloading
3) http://www.php-fig.org/psr/psr-0/

Upvotes: 1

Related Questions