Search code examples
phpsymfonydomdocument

Unable to use DOMDocument in Symfony


I have been unable to use DOMDocument in symfony. After digging around, I found the problem might be that I do not have the php xml extension, but I thought that it was absurd because, despite no being able to use DOMDocument, I can use Symfony's DOMCrawler, which obviously uses something similar to DOMDocument. Well, After looking through Crawler's source code, I found they uses something like

$dom = new \DOMDocument('1.0', $charset);    

instead of the usual

$dom = new DOMDocument('1.0', $charset);

Does someone know the difference between the two, and why one works and the other doesn't in Symfony?


Solution

  • Because in symfony we use namespace in each class. And because you have declared a namespace in your class then you need to inform PHP about the namespaces of each class you want to use. If you do not declare the namespace of a class you are using, PHP will think this class is in the same namespace than the current class.

    So the backslash "\" in this code: new \DOMDocument() is there to informe PHP that you want to use the DOMDocument class from the "global" namespace. If you want to use the Datetime object you will also need to use a backslash when instantiating the Datetime object.

    Another solution is to declare with the keyword Use. For exemple:

    use \DOMDocument;
    

    And then in your code you will instanciate without backslash: new DomDocument()