Home > Article > Backend Development > 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:
<div class="main"> <div class="text"> Capture this text 1 </div> </div> <div class="main"> <div class="text"> Capture this text 2 </div> </div>
To retrieve the text within the
php $html = <<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.
The above is the detailed content of How to Extract Text from Specific HTML Tags Using DOMDocument and XPath?. For more information, please follow other related articles on the PHP Chinese website!