
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
Parse HTML with PHP's HTML DOMDocument
The text inside a <div> tag inside class="text" inside <div> with class="main" can be obtained with the following code −
Example
$html = <<<HTML <div class="main"> <div class="text"> This is text 1 </div> </div> <div class="main"> <div class="text"> This is text 2 </div> </div> HTML; $dom = new DOMDocument(); $dom->loadHTML($html); $xpath = new DOMXPath($dom); XPath queries along with the DOMXPath::query method can be used to return the list of elements that are searched for by the user. $tags = $xpath->query('//div[@class="main"]/div[@class="text"]'); foreach ($tags as $tag) { var_dump(trim($tag->nodeValue)); }
Output
This will produce the following output −
string ‘This is text 1’ (length=14) string ‘This is text 2' (length=14)
- Related Articles
- How to Parse HTML pages to fetch HTML tables with Python?
- How to parse HTML in android?
- How to parse HTML in Android using Kotlin?
- PHP Escaping From HTML
- HTML DOM S Object
- Make JavaScript take HTML input from user, parse and display?
- Disabling Android's chrome pull-down-to-refresh feature with HTML.
- JavaScript to parse and show current time stamp of an HTML audio player.
- Can HTML be embedded inside PHP “if” statement?
- How to display XML in HTML in PHP?
- Ember.js browser support with HTML
- HTML DOM HTML Object
- How to parse a CSV file using PHP
- Client-side image processing with HTML
- Position your HTML element with CSS

Advertisements