PHP DOM Parser Example

please click here for more wordpress cource

Sure! Here’s an example of how to use the PHP DOM Parser to extract information from an HTML document:

// Load the HTML file into a DOM object
$dom = new DOMDocument();

// Find all the <a> tags and extract their href attributes
$links = $dom->getElementsByTagName('a');
foreach ($links as $link) {
    $href = $link->getAttribute('href');
    echo $href . '<br>';

// Find the first <h1> tag and extract its text content
$h1 = $dom->getElementsByTagName('h1')->item(0);
echo $h1->textContent;

This example loads an HTML file into a DOM object and then uses various methods to extract information from it. The getElementsByTagName method is used to find all the <a> tags and the first <h1> tag. The getAttribute method is used to extract the href attribute of each <a> tag, and the textContent property is used to extract the text content of the first <h1> tag.

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *