'How to convert an html string to an html object in php

How do i convert an html string to an html object in php like the object returned by file_get_html();

$html_string = "<html><body>hi</body></html>"; //this returns a string

I want to convert $html_string into an object and parse it using simple_html_dom

php


Solution 1:[1]

You can use the DOMDocument class. To load your HTML string to a DOM object you have to use the loadHTML method.

Then you are able to manipulate the DOM by using the DOMXPath class. working example

<?php
$html_string = "<html><body>hi</body></html>";
$string = <<<HTML
$html_string
HTML;

$dom = new DOMDocument();
$dom->loadHTML($string);


$xpath = new DOMXpath($dom);
$result = $xpath->query('//body');
if ($result->length > 0) {
    var_dump($result->item(0)->nodeValue);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Maik Lowrey