"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Extract Text from Specific HTML Tags Using DOMDocument and XPath?

How to Extract Text from Specific HTML Tags Using DOMDocument and XPath?

Posted on 2025-03-10
Browse:993

How to Extract Text from Specific HTML Tags Using DOMDocument and XPath?

Parsing HTML with PHP's DOMDocument and XPath

When attempting to parse HTML using PHP's DOMDocument, a common issue is finding specific text within tags of particular classes. Using DOMDocument::getElementsByTagName alone may not suffice in such cases.

To capture specific text within tags of a target class, an alternative approach utilizing DOMDocument and DOMXPath is recommended. DOMXPath allows for powerful XPath queries to locate elements based on their attributes and structure.

Consider the following HTML:

Capture this text 1
Capture this text 2

To retrieve the text within the

tags with class="text" that are descendants of the
tags with class="main", follow these steps:
php
$html = 
    
Capture this text 1
Capture this text 2
HTML; $dom = new DOMDocument(); $dom->loadHTML($html); $xpath = new DOMXPath($dom); $tags = $xpath->query('//div[@class="main"]/div[@class="text"]'); foreach ($tags as $tag) { var_dump(trim($tag->nodeValue)); }

This code snippet will output:

string 'Capture this text 1' (length=19)
string 'Capture this text 2' (length=19)

By utilizing DOMDocument and DOMXPath, you can accurately locate and retrieve elements within an HTML structure, even when dealing with specific class hierarchies and content requirements.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3