Reputation: 1107
I have two div tags with the same class name one after the other:-
HTML:
<div class='random'>
<div class="name">
<h1>Title 1</h1>
<p>Description</p>
</div>
<div class="name">
<h1>Title 2</h1>
<p>Other Description</p>
</div>
</div>
<div class='random'>
<div class="name">
<h1>Title 2-1</h1>
<p>Description2</p>
</div>
<div class="name">
<h1>Title 2-2</h1>
<p>Other Description2</p>
</div>
</div>
.....
.....
Now I want to get both descriptions seperately:
Output 1 desired:-
DescriptionOutput 2 desired:-
Other DescriptionBut My output:
Description
Other Description
Code:
foreach($html->find('div.name p') as $value)
{
echo $value->innertext;
}
Is there any way such that we can specify only the first class or second class to be printed?
Upvotes: 0
Views: 8326
Reputation: 345
Just use this code
echo $htmlEN->find('.name h1', 0)->innertext;
echo $htmlEN->find('.name p', 0)->innertext;
and
echo $htmlEN->find('.name h1', 1)->innertext;
echo $htmlEN->find('.name p', 1)->innertext;
......
Upvotes: 0
Reputation: 766
// Find (N)th anchor, returns element object or null if not found (zero based)
$ret = $html->find('a', 0);
// Find lastest anchor, returns element object or null if not found (zero based)
$ret = $html->find('a', -1);
Try this. It helps!
Upvotes: 1
Reputation: 54984
First class(es):
$html->find('div.name[1] p')
Second class(es):
$html->find('div.name[2] p')
Upvotes: 4
Reputation: 6950
Try this code
$count = count($html->find('div.name p'));
for($index=0; $index<$count; $index++)
{
$text = getElementByIndex($html, $index);
echo "output $index : $text";
}
function getElementByIndex($html,$index)
{
return $html->find('div.name p', $index);
}
Hope it helps you ..
Upvotes: 0
Reputation: 3814
PHP Simple HTML DOM Parser Manual
mixed find ( string $selector [, int $index] ) Find children by the CSS selector. Returns the Nth element object if index is set, otherwise, return an array of object.
Don't use a loop, instead do something like this:
echo "Output 1 desired:-<BR>";
echo $html->find('div.name p', 0) . "<BR>";
echo "Output 1 desired:-<BR>";
echo $html->find('div.name p', 1);
Upvotes: 0