23
votes

I'm using PHP's built-in DOMDocument() class to do some simple web-scraping. However, it works on my 4.2 site, but not my 5.1 (both are on same installation of PHP).

Here's the error:

Class 'App\Http\Controllers\III_Ranks\DOMDocument' not found

Here's my controller:

<?php

namespace App\Http\Controllers\III_Ranks;

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use Illuminate\Http\Response;

class RanksController extends Controller 
{
    public function getRanks()
    {
        $list1 = new DOMDocument();
        //etc...
    }
}

I figure this is a namespace issue, but I have no idea how to access DOMDocument()

Thanks for any help.

5

5 Answers

49
votes

In Laravel 5.1 you must prefix the class name with the global namespace prefix '\'.

So your updated code:

<?php

namespace App\Http\Controllers\III_Ranks;

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use Illuminate\Http\Response;

class RanksController extends Controller 
{
    public function getRanks()
    {
        $list1 = new \DOMDocument();
        //etc...
    }
}
10
votes

For me, in order to solve the error: DOMDocument() class not found. I had to install the DOM extension.

If you are using PHP 5:

You can do so on Debian / Ubuntu using:

sudo apt-get install php5-dom

And on Centos / Fedora / Red Hat:

yum install php-xml

If you are using PHP 7:

For Ubuntu:

apt-get install php7.0-xml

For CentOS / Fedora / Red Hat:

yum install php70w-xml
5
votes

Tested in Laravel 5.4

you can use keyword use :

In top of file before define the class you can write use DOMDocument; instead of new \DOMDocument();

For eg:

<?php

namespace App\Http\Controllers\III_Ranks;

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use Illuminate\Http\Response;

use DOMDocument;

class RanksController extends Controller {
...

what is this '...' ?

1
votes

I had this problem in laravel 5.6 on a server with ubuntu 16.04, and I solved this issue installing the xml package for php7.1 version, this does not work for me in the php7.2 version I don't know why.

1.- Make sure you have the version 7.1 of php installed, I use this command to select the correct php version in ubuntu:

update-alternatives --set php /usr/bin/php7.1

Note: In case you don't have installed the php7.1 version, do you need to install it before the above command, in that case you can use this command: apt-get install php7.1

2.- To install the package XML I was used the following command:

apt-get install php7.1-xml

3.- Restart your apache server, in my case with this command:

service apache2 restart

I hope to be helpful, this saved my day.

1
votes

I had the same issue with Amazon Linux 2 (LAMP) with laravel framework

Please find below steps resolve issues:

 sudo systemctl stop httpd 
 sudo yum install  php-xml
 sudo systemctl start httpd