Reputation: 115
I want to parse html using the php. My html file is like this
<div class="main">
<div class="text">
Welcom to Stackoverflow
</div>
</div>
now i want to extract the only this part
<div class="text">
Welcom to Stackoverflow
</div>
for this i create the code like this
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$tags = $xpath->query('//div[@class="main"]');
foreach ($tags as $tag) {
var_dump(trim($tag->nodeValue));
}
this code gives only the
Welcom to Stackoverflow
but i want the tag also. how to do this??
Upvotes: 0
Views: 82
Reputation: 3209
The Querypath library for html/xml parsing makes such things much much easier.
Upvotes: 0
Reputation: 2792
If you only want to have the div with class "text" try this:
Change your query to: $xpath->query('//div[@class="text"]');
For the output you need: echo $dom->saveHTML( $tag );
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$tags = $xpath->query('//div[@class="text"]');
foreach ($tags as $tag) {
echo $dom->saveHTML( $tag );
}
Upvotes: 2