Home > Backend Development > PHP Tutorial > How to Extract Text from Specific HTML Tags Using DOMDocument and XPath?

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

Linda Hamilton
Release: 2024-10-31 13:14:20
Original
617 people have browsed it

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>
Copy after login

To retrieve the text within the

tags with class="text" that are descendants of the
tags with class="main", follow these steps:

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));
}
Copy after login

This code snippet will output:

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

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template