teeyo
teeyo

Reputation: 3755

DOMDocument not found

I'm trying to code my own "HTML Generator" so i won't have to write HTML as string anymore, but the problem is that PHP doesn't recognize the DOMDocument class, it tries to load a Class with the name DOMDocument in the same namespace, which throws the error, I tried adding the backslah but no luck, here's my code :

<?php

namespace Services\HtmlGenerator;

use \DOMDocument;

/**
* Services\HtmlGenerator\Html
*/
class Html extends DOMDocument
{

    function __construct(){
         parent::__construct('1.0','iso-8859-1' );
         $this->formatOutput = true;
    }

    public function createInput($value, $name, $class = null)
    {
        $input = $this->createElement('input');
        $input->setAttribute('value', $value);
        $input->setAttribute('name', $name);
        $input->setAttribute('class', $class);
        return $input;
    }
}

the code of the action in the controller that uses this class :

<?php

namespace ModuleX\RemoteControllers;

use Services\HtmlGenerator\Html;
//...

class RemoteXController extends RemoteController
{
 //...
public function action()
{
    $html = new Html;
    $elem = $html->createInput('test', 'test', 'test');
    $html->appendChild($elem);
    return $html->saveHTML();

Here's the error message :

Fatal error: Class 'Services\HtmlGenerator\DOMDocument' not found in C:\xampp\htdocs\erp\services\htmlGenerator\Html.php on line 10

I'm using XAMPP 1.8.3 with PHP 5.5.15 on a Windows 7 machine.

I also want to mention that when I use $html = new \DOMDocument; in my controller it works just fine.

Upvotes: 0

Views: 3312

Answers (3)

Sean Colombo
Sean Colombo

Reputation: 1519

This can often be caused by not having the right modules installed for PHP. If your server is running a Linux distro (like CentOS) that supports YUM, you can install it with a command like this:

yum install php-xml.x86_64

Then simply restart apache (eg: /etc/init.d/httpd restart) and it should be ready to go.

Upvotes: 1

user1187347
user1187347

Reputation: 328

When extending a class from another namespace, you need to use a fully qualified name for the extends statement. For example:

<?php

namespace Services\HtmlGenerator;

class Html extends \DOMDocument
{
...
}

Note the leading backslash on the extends statement

Upvotes: 1

RichardBernards
RichardBernards

Reputation: 3097

Add use \DOMDocument; after the namespace line

Upvotes: 1

Related Questions