How to Use loadHTML, loadHTMLFile, and loadXML functions in PHP?
In PHP programming there might be scenarios where you need to load html strings, html files, and xml strings. These can be easily done using the functions available in PHP for this purpose. Functions like loadHTML, loadHTMLFile, and loadXML can be used to do these tasks.
The loadHTML function can be used to load the html content available in a string source. It is not necessary that the string source should have well-formed html. It is possible to call this function statically when there is no need to set any DOMDocument properties before you load it.
The following example shows how this function is used to load an html string.
$webDoc = new DOMDocument();
$webDoc->loadHTML("<br><br><B>Load Third html string</B>");
The output of the above code is show in the figure below:
Using loadHTMLFile to load an html file
You can use the loadHTMLFile function to load an html file by specifying the path of the filename. You can also invoke this function statically if you don't need to set any DOMDocument property. An example that uses this function is given below.
Consider an HTML file that has the code,
<h3>This is an external html file</h3>
This code is stored in the name of webpage.htm.
You can use the following code to load this html file and display it in the browser.
The output for the above code is given as below:
Using loadXML function to load an XML string
With the loadXML function you can load the xml string from a string source. Like other load functions you can also invoke this function statically, if you are not going to set any DOMDocument property.
$strxml = <<<XML
$newdom = new domDocument;
In the above code the variable $strxml is loaded with the xml string and then the loadXML file is called to load the xml in to the DOMDocument. Two elements of the node candidate is displayed using the code above.
The output for the above code is given below: